react.js - react-router4 路由变了页面没变

查看:1331
本文介绍了react.js - react-router4 路由变了页面没变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

url已经变了,但是页面没变。
当我在render里面使用 return <Redirect ... />,页面居然跳转成了空白。用this.props.history.push 或者this.props.history.replace在各个生命周期里使用,顶部路由也变了,但是页面没点动静。

我的代码:

//入口
ReactDOM.render(
  <Provider store={store}>
    <Router basename="/">
      <div>
        <Switch>
          <Route path="/login" component={LoginContainer} />
          <Route
            path="/" render={(props) => {
            return store.getState().userReducer.authenticated || localStorage.getItem('token') ? <AppContainer /> : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />;
          }
          }
          />
        </Switch>
      </div>
    </Router>
  </Provider>,
  MOUNT_NODE
);

//class AppContainer
render() {
    return (
      <div>
        <Route exact path="/" component={HomeContainer}/>
        <Route exact path="/bindBank" component={BindBankContainer}/>
        <Route exact path="/goPay" component={GoPayContainer}/>
        <Route exact path="/pay" component={PayContainer}/>
      </div>
    );
  }

export default connect(mapStateToProp, mapDispatchToProp)(withRouter(AppContainer));

//class GoPayContainer
render() {
    
    //链接回溯
    const {from} = this.props.location.state || {from: {pathname: '/pay'}};

    //进入支付密码界面
    if(this.props.goPayed) {
      this.props.history.replace({pathname:'/pay'});
    }
    /*if(this.props.goPayed) {
      return (<Redirect to={{
        pathname: '/pay',
        state: { from: this.props.location }
      }} />);
    }*/
   
...
}

const WrappedGoPay = Form.create()(GoPayContainer);
export default connect(mapStateToProp, mapDispatchToProp)(withRouter(WrappedGoPay));

直接访问/pay路由是没问题的

求大神解救啊···

解决方案

错误的地方就在类似这样的代码

写法1

export default connect(mapStateToProp, mapDispatchToProp)(withRouter(AppContainer));

应该写成

写法2


export default withRouter(connect(mapStateToProp, mapDispatchToProp)(AppContainer));

原因

connect内是进行shallow comparison浅比较的。它重写了组件的shouldComponentUpdate方法

写法1中,connect重写了withRouter的shouldComponentUpdate方法,导致其不能够响应location的变化(仅仅响应mapStateToProps里面的变化)

写法2中,将withRouter提到外层,withRouter的shouldComponentUpdate不会被重写,就会响应location的变化

这篇关于react.js - react-router4 路由变了页面没变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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