在 react-router-dom 中重定向? [英] Redirect in react-router-dom?

查看:88
本文介绍了在 react-router-dom 中重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我开始使用 react/redux 以来,我第一次使用 react-router-dom 应用程序,但在使用 Redirect 组件时遇到了问题.

我想在身份验证成功时触发 Redirect 但它在身份验证后没有重定向到我想要的页面.

index.js

import { BrowserRouter as Router, Route } from 'react-router-dom';import { createStore, applyMiddleware } from 'redux';从'redux-thunk'导入ReduxThunk;从'./components/app'导入应用程序;从 './containers/page1' 导入 Page1;从'./containers/auth/signin'导入登录;从'./reducers'导入Reducers;const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);const store = createStoreWithMiddleware(Reducers);ReactDOM.render(<提供者商店={商店}><路由器><div><Route path="/" component={App}/><Route path="/" component={Signin}/><Route path="/signin" component={Signin}/><Route path="/page1" component={Page1}/>

</路由器></提供者>, document.querySelector('.container'));

登录.js

import { BrowserRouter as Route, Redirect } from 'react-router-dom';从 '../../actions/index' 导入 { userSignin };类登录扩展组件{构造函数(道具){超级(道具);this.state = { 用户名:'',密码:'' };this.handleSubmit = this.handleSubmit.bind(this);this.handleUsernameChange = this.handleUsernameChange.bind(this);this.handlePasswordChange = this.handlePasswordChange.bind(this);}componentWillUpdate(nextProps) {如果 (this.props.authenticated !== nextProps.authenticated) {如果(nextProps.authenticated){console.log('true?', nextProps.authenticated)返回 (<重定向到="/page1"/>);}}}处理提交(e){e.preventDefault();this.props.userSignin({ 用户名: this.state.username, 密码: this.state.password });this.setState({ 用户名:'', 密码:'' });}.....使成为() {返回 (<form onSubmit={this.handleSubmit}><输入占位符=用户名"值={this.state.username}onChange={this.handleUsernameChange}/><输入占位符=密码"类型=密码"值={this.state.password}onChange={this.handlePasswordChange}/><跨度><button type="submit">SIGNIN</button></span>{this.renderError()}</表单>);}}函数 mapStateToProps(state) {返回 {已认证:state.auth.authenticated,错误消息:state.auth.err};}函数 mapDispatchToProps(dispatch) {返回 {用户登录:({用户名,密码})=>调度(用户登录({用户名,密码}))};}导出默认连接(mapStateToProps,mapDispatchToProps)(登录);

在这段代码中,这确实记录了 true? 但它不会重定向到 /page1.

正如我所提到的,这是我第一次使用 react-router-dom 库,对于我的代码中出现的任何愚蠢错误,我深表歉意.

谢谢你,请洞察我!

解决方案

代替 Redirect 使用 this.props.history.push('/path1') 并换行withRouter 中的 connect()(从 react-router 导入)像这样:

导出默认 withRouter(connect(mapStateToProps, mapDispatchToProps)(Signin));

如果要使用Redirect,在本地状态维护认证值,在componentWillReceiveProps中更新,并在render方法中有条件地渲染.

I'm working on react-router-dom app for the first time since I started using react/redux and I'm having a trouble with using Redirect component.

I want to fire Redirect when authentication is successful but it does not redirect to the page that I want after authentication.

index.js

import { BrowserRouter as Router, Route } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';

import App from './components/app';
import Page1 from './containers/page1';
import Signin from './containers/auth/signin';

import Reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);
const store = createStoreWithMiddleware(Reducers);

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <div>
        <Route path="/" component={App}/>
        <Route path="/" component={Signin}/>
        <Route path="/signin" component={Signin}/>
        <Route path="/page1" component={Page1}/>
      </div>
    </Router>
  </Provider>
, document.querySelector('.container')); 

signin.js

import { BrowserRouter as Route, Redirect } from 'react-router-dom';

import { userSignin } from '../../actions/index';

class Signin extends Component {
  constructor(props) {
    super(props);

    this.state = { username: '', password: '' };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
  }

  componentWillUpdate(nextProps) {
    if (this.props.authenticated !== nextProps.authenticated) {
      if (nextProps.authenticated) {
        console.log('true?', nextProps.authenticated)
        return (
          <Redirect to="/page1" />
        );
      }
    }
  }

  handleSubmit(e) {
    e.preventDefault();
    this.props.userSignin({ username: this.state.username, password: this.state.password });
    this.setState({ username: '', password: '' });
  }
  .....

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          placeholder="username"
          value={this.state.username}
          onChange={this.handleUsernameChange}
        />
        <input
          placeholder="password"
          type="password"
          value={this.state.password}
          onChange={this.handlePasswordChange}
        />
        <span>
          <button type="submit">SIGNIN</button>
        </span>
        {this.renderError()}
      </form>
    );
  }
}

function mapStateToProps(state) {
  return {
    authenticated: state.auth.authenticated,
    errMsg: state.auth.err
  };
}

function mapDispatchToProps(dispatch) {
  return {
    userSignin: ({ username, password }) => dispatch(userSignin({ username, password }))
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Signin);

In this code, this does log true? but it does not redirect to the /page1.

As I mentioned, this is my first time using react-router-dom library and I apologize for any dumb mistake that I have in my code.

Thank you and please insight me!

解决方案

Instead of Redirect use this.props.history.push('/path1') and wrap the connect() in withRouter(import from react-router) like this:

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Signin));

If you want to use Redirect, maintain the authenticated value in the local state , update it in componentWillReceiveProps and conditionally render the <Redirect /> in render method.

这篇关于在 react-router-dom 中重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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