使用 React Router 4 对组件内的 url 更改做出反应? [英] React to url change within component with React Router 4?

查看:40
本文介绍了使用 React Router 4 对组件内的 url 更改做出反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可在不同网址上使用的组件.这是我的 app.js 的简化版本

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>

我传递了状态道具,然后根据道具值在组件 setState 中传递.到目前为止,这有效,但我还需要链接到其他其他状态的组件内的链接.当您在注册页面/状态时,我有一个登录链接.当您在登录页面/状态时,我有一个注册链接.

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.

这意味着我必须有一个链接来更改 url 并调用一个函数来设置状态:

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>

如何在检测到 url 更改时更改组件状态?似乎 browserHistory 在 v4 之前做到了这一点,但我找不到最新的解决方案.

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.

推荐答案

我可以在 SignUpAndRegister 组件第一次安装时设置状态,然后在每次收到新道具时(例如,当 url 更改时).

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 });
}

这篇关于使用 React Router 4 对组件内的 url 更改做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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