首页 > 解决方案 > withRouter 不能与 redux 一起正常工作 - react redux react-router

问题描述

这是我在authReducer.

const initialState = {
    token:'',
    isLogin:  false,
    error: {}
};
function AuthReducer(state = initialState, action) {
    switch(action.type){
        case AUTH_SUCCESS:
            return sessionStorage.setItem('token',action.payload),{
                ...state,
                isLogin: true,
                token: action.payload,
                error: {}
            };
        case AUTH_FAILED:
            return {
                ...state,
                isLogin: false,
                token: '',
                error: action.payload
            };
            default:
            return state
    }
}
export default AuthReducer;

这是我的登录组件,工作正常。用户可以进行身份​​验证,一切正常:

class Login extends Component {
    constructor(props){
        super(props);
        this.state ={
            username: '',
            password: ''
        }
    }
    onSubmit = e => {
        e.preventDefault();

        this.props.login(this.state.username, this.state.password);
    }
    
    render() {
       .....
        )
    }
}

const mapStateToProps = state => {
    return {
        get: { auth : state.AuthReducer}
    }
}
const mapDispatchToProps = dispatch => {
    return {
        login: (username, password) => {
            return dispatch(login(username, password));
        }
    };
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Login));

我的路由器是这样的:

class App extends Component {
  constructor(props){
    super(props)
  }
  render() {
    let PrivateRoute = ({ component: ChildComponent, isLogin, ...rest}) => {
      console.log({...rest}, "this is rest")
      return <Route 
      {...rest}
        render={props => {
          if (!isLogin) {
            return <Redirect to="/login" />;
        } else {
          return <ChildComponent {...props} />
        }
      }} />
    }
    return (
      <div>
          <Home />
          <Switch>
          <PrivateRoute path="/" exact isLogin={this.props.auth.isLogin}  component={mainContent} />
          <PrivateRoute path="/posts" isLogin={this.props.auth.isLogin} component={Posts} />
          <Route path="/login"  component={Login} />
        </Switch>
      </div>
    );
  }
}
const mapStateToProps = state => {
  return {
    auth: state.AuthReducer
  }
}
const mapDispatchToProps = dispatch => {
  return {
    getUser: () => {
      return dispatch(getUser());
    }
  };
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

在 react-router 中,他们说你必须withRouter从 react-router-dom 使用。我的问题是登录工作正常。但我无法访问我的道具,privateroute所以当反应呈现一个新页面时,我的isLogin设置为 false。我有一些想法,路由器不知道我的 redux 或受保护的组件不能不知道 props 的变化。我的所有子组件PrivateRoute都与 react-redux 连接。

标签: reactjsreduxreact-router

解决方案


这里的问题是您没有从减速器获得 isLogin 值。当您尝试在路由器文件中获取减速器值时:

const mapStateToProps = state => {
  return {
    auth: state.AuthReducer
  }
}

您将得到this.props.auth.AuthReducer未定义的state值,因为 mapStateToProps 中的值将是您的 reducer 的初始值。因此,您可以像下面这样直接从状态获取登录并尝试访问this.props.auth

const mapStateToProps = state => {
  return {
    auth: state.isLogin
  };
};

或者你可以用这个替换你的代码并使用this.props.auth.isLogin

const mapStateToProps = state => {
  return {
    auth: state
  };
};

更多信息请参考: https ://codesandbox.io/s/react-router-dom-with-private-route-sr61v


推荐阅读