【问题标题】:React + Redux best practice for router redirecting on redux state changeReact + Redux 在 redux 状态更改时重定向路由器的最佳实践
【发布时间】:2019-04-16 09:27:57
【问题描述】:

我正在使用 react-router-dom,我正在尝试将它与 redux 绑定。我想在行动中重定向,但不知道最好的方法是什么。我需要使用 history.push() 还是其他东西?也许 React 有这方面的原生方法?

我的组件容器代码:

class ConnectedAppContent extends React.Component {
    render() {
        return (
            <div id="content">
                <Router>
                    <Switch>
                        <PropsRoute path="/login" component={LoginForm} doLogin={this.props.doLogin} />
                        <PrivateRoute path="/scan" redirectTo="/login" component={Scanner} token={this.props.token} />
                        <PrivateRoute path="/result" redirectTo="/login" component={ParsedQRCode} token={this.props.token} />
                    </Switch>
                </Router>
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        token: state.token,
        parsedQRCode: state.parsedQRCode
    }
}

const mapDispatchToProps = dispatch => ({
    doLogin: token => dispatch(doLogin(token))
});

export const AppContent = connect(mapStateToProps, mapDispatchToProps)(ConnectedAppContent);

【问题讨论】:

    标签: javascript reactjs redux react-redux react-router


    【解决方案1】:

    如果您想在按钮单击或提交时路由到某个事件的特定路径,您可以使用 react-router-dom 提供的 Redirect 或 Link。

    此外,react-router 可以与 redux 一起使用,但在某些情况下它不能,您可以使用 withRouter 包装您的组件,然后您可以使用以下命令轻松推送路由:

    history.push('/your-route')
    

    【讨论】:

      【解决方案2】:

      我愿意

      import {Redirect} from 'react-router-dom';
      

      在渲染方法中你可以:

        render() {
      
          if (yourRedirectState) {
            return <Redirect to='/route'/>;
          }   
      }
      

      【讨论】:

        【解决方案3】:

        我不知道任何其他方法,但 history.push() 可以工作

        const stateChange = () => {
          this.props.doLogin();
          this.props.history.push("/routetoredirect")
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-04
          • 2022-12-01
          • 2016-10-21
          • 2016-11-26
          • 2021-08-19
          • 2019-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多