React to url change within component with React Router 4?

我怕爱的太早我们不能终老 提交于 2019-12-11 18:09:19

问题


I have a component available at different urls. This is a simplified version of my app.js

<Router>
        <Switch>
            <Route path="/login"
               render={() => {
                    return <SignUpAndRegister status="login" />;
                }}
            </Route>
            <Route path="/register"
                render={() => {
                    return <SignUpAndRegister status="register" />;
                }}
            </Route>
        </Switch>
    <Router>

I pass the status prop and then in the component setState based on the prop value. This works so far but I also need Links within the component that link to other other state. When your on the register page/state I have a link to login. When you're on the login page/state I have a link to register.

This means I have to have a link to change the url and also call a function to setState:

    <Link
      to="/login"
      onClick={() => this.registerOrLogin('login')}
      >
        Log in
    </Link>

How can I have the components state change when a url change is detected? It seems like browserHistory did this prior to v4 but I cant find an up up date solution.


回答1:


I can set the state within the SignUpAndRegister component when it first mounts and then every time new props are received eg when the url changes.

componentDidMount() {
    this.setState({ status: this.props.status });
}

componentWillReceiveProps(props) {
    this.setState({ status: props.status });
}


来源:https://stackoverflow.com/questions/49913058/react-to-url-change-within-component-with-react-router-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!