【问题标题】:Browser URL updates but components do not update along浏览器 URL 更新,但组件不随之更新
【发布时间】:2018-06-26 15:15:15
【问题描述】:

我有一个带有三个链接的导航栏。如果我单击一个链接,URL 会更新并导航到/categories/categoryID。我第一次单击链接时一切正常。但它只工作一次。如果我单击另一个类别(导航栏中的链接更改类别),内容不会改变。但是,当我刷新浏览器时,它会改变。

  1. 我点击导航栏中的链接
  2. 网址更改正确
  3. 组件不会重新渲染
  4. 如果我刷新浏览器,则会加载正确的内容

URL 和组件的重新呈现之间似乎存在脱节。

问题:断开连接的原因是什么?

我怀疑这种行为的原因是我对 react 路由器 (v4) 的实现。

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
        <div>
            <Header />
            <Switch>
                <Route path="/categories/index/:uuid/" component={CategoryIndex} />
                <Route path="/user/signup" component={SignUpForm} />
                <Route path="/user/login" component={LoginForm} />
                <Route path="/home/" component={IndexPage} />
            <Route/> 
            </Switch>
        </div>
    </BrowserRouter>
    </Provider>
    , document.getElementById('root'));
registerServiceWorker();

不重新渲染的组件如下所示:

class PostList extends Component {

    componentDidMount() {
        const { uuid } = this.props.match.params;
        this.props.fetchCategoriePosts(uuid);

    }

    renderPostList() {
        const { category } = this.props;
        if (category) {
            return (
                _.map(category, post => {
                    return(
                        <li className="list-group-item" key={post.uuid}>
                        <div>Hallo</div>
                        <Link to="/">{post.title}</Link>
                        </li>
                    )
            }));
        }
    }

    render() {
        return (
            <div className="container">
                <ul className="list-goup">
                    {this.renderPostList()}
                </ul>
            </div>
        );
    }
}

function mapStateToProps({ category }) {
    return {category}
}

export default connect(mapStateToProps, {fetchCategoriePosts}) (PostList);

有人可以帮忙吗?

【问题讨论】:

  • 你是怎么改网址的?
  • 使用 react-router-dom 中的链接组件。
  • 您是否有机会也可以提供minimal reproducible example,这会让我们继续猜测;)您的控制台中是否有任何警告或错误?
  • 首先renderPostList没有被绑定,其次你应该检查这个stackoverflow.com/questions/44356360/…
  • 我什至没有在你的路由器中看到PostList,如果父级没有安装或卸载也没有接收新的道具/状态,它不会呈现任何新的

标签: reactjs react-router react-redux


【解决方案1】:

您是否尝试过使用 react-router-dom 中的 withRouter 包装您的导出?当与 React Router 结合使用时,Redux 有时会劫持生命周期方法。我在更新 url 时遇到了类似的问题,但显示了一个空白页面,并且通过以下方式取得了成功:

export default withRouter(connect(mapStateToProps, {fetchCategoriePosts}) (PostList));

【讨论】:

  • 是的,我试过了。但在那种情况下它不起作用。
【解决方案2】:

这似乎是一个 React 生命周期问题。我假设您希望您的组件更新而不是在 URL 更改时重新呈现。

componentWillUpdate(nextProps) {
  const { uuid } = nextProps.match.params;
  if (uuid !== this.props.params.match.uuid) {
    this.props.fetchCategoriePosts(uuid);
 }
}

(如果你听事件LOCATION_CHANGE,你也可以在你的传奇中做到这一点)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多