当点击 <Link> 时,react-router 4 不会更新 UI [英] react-router 4 doesn't update UI when clicking <Link>

查看:49
本文介绍了当点击 <Link> 时,react-router 4 不会更新 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-router-dom 4.1.1 编写一个带有导航栏和 5 个路由的小应用程序.当我点击导航栏中的链接时,Firefox 地址栏中的 URL 会更新,但显示的页面没有改变.但是,如果我在地址栏中输入子页面的地址,则会显示正确的页面.

app.js:

render(<提供者商店={商店}><HashRouter><主容器/></HashRouter></提供者>,document.querySelector('.app'));

Main.js:

render() {返回 (<div className="main"><Message message= {this.props.message}/><导航栏/><开关><路由精确路径="/" component={HomePage}></Route><Route path="/classify" component={ClassifyPage}></Route><Route path="/admin" component={AdminPage}></Route><Route path="/users" component={UsersPage}></Route><Route path="/help" component={HelpPage}></Route></开关>

);}

解决方案

似乎某些组件,例如使用 connect() 的 react-redux 容器,会阻止更新.使用 withRouter() 解决了问题:

const MainContainer = withRouter(connect(mapStateToProps,mapDispatchToProps)(主要的));

文档:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

I am writing a small app with a navigation bar and 5 routes using react-router-dom 4.1.1. When I click on a link in the navigation bar, the URL in the Firefox address bar updates, but the page displayed does not change. However, if I enter the address of a subpage in the address bar, the correct page is displayed.

app.js:

render(
    <Provider store={store}>
        <HashRouter>
            <MainContainer />
        </HashRouter>
    </Provider>,
    document.querySelector('.app')
);

Main.js:

render() {
    return (
        <div className="main">
            <Message message= {this.props.message} />
            <NavigationBar />
            <Switch>
                <Route exact path="/" component={HomePage}></Route>
                <Route path="/classify" component={ClassifyPage}></Route>
                <Route path="/admin" component={AdminPage}></Route>
                <Route path="/users" component={UsersPage}></Route>
                <Route path="/help" component={HelpPage}></Route>
            </Switch>
        </div>
    );
}

解决方案

It seems some components, like react-redux containers using connect(), block updates. The problem was solved using withRouter():

const MainContainer = withRouter(connect(
        mapStateToProps,
        mapDispatchToProps
      )(Main));

Documentation: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

这篇关于当点击 &lt;Link&gt; 时,react-router 4 不会更新 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆