0

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路由是没问题的

求大神解救啊···

2个回答

1

已采纳

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

写法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的变化

0

react & react-dom 是15.x么,不是就是升级了试试

撰写答案