首页 > 解决方案 > react-router4 更改了 URL,但路由与要渲染的新 URL 不匹配

问题描述

标签: reactjsreact-routerreact-router-v4

解决方案


由于您this.props.history.push在 Routes 组件中使用,因此您需要将此组件包装为withRouter

class Routes extends Component {

  constructor(props) {
    super(props);
    this.URLChange = this.URLChange.bind(this);
    this.getOwnState = this.getOwnState.bind(this);

    this.state = this.getOwnState();
  }

  getOwnState() {
    return {
      currentURL: store.getState()["currentURL"]
    };
  }

  URLChange() {
    console.debug(this.getOwnState()["currentURL"]);
    this.props.history.push(this.getOwnState()["currentURL"]);

    //setState是异步的
    let currentURL = this.getOwnState()["currentURL"];
    this.setState(Object.assign({
      currentURL
    }, {currentURL}), () => {
      //回调方法
      console.debug("1:" + this.state.currentURL)
    })

  }

  componentDidMount() {
    store.subscribe(this.URLChange);
  }

  render() {
    alert("render:" + JSON.stringify(this.props.history.location.pathname));
    return (<BrowserRouter >
      <Switch>
        <Route path="/LoginPage" component={LoginPage}/>
        <Route path="/SuccessPage" component={SuccessPage}/>
        <Route path="/errorPage" component={errorPage}/>
        <Route path="/*" component={errorPage}/>
      </Switch>
    </BrowserRouter>);
  }
}

export default withRouter(Routes);

推荐阅读