使用getDerivedStateFromProps替换redux中的componentWillReceiveProps但不触发

时间:2018-05-05 04:33:24

标签: javascript reactjs redux

我在使用带有redux的getDerivedStateFromProps时遇到了问题。我想替换componentWillReceiveProps升级以反应16,但不知怎的,它不会被解雇。下面是我的容器组件代码

@connect(state=>({user: state.user, global: state.global}), {loginUser})
class LoginFormContainer extends React.Component {

  constructor() {
    super()
    this.state = {
      email: '',
      password: '',
      isAuthenticated: false
    }
  }

  //but this worked?
  componentWillReceiveProps(nextProps) {
    if(nextProps.user.isAuthenticated !== this.props.user.isAuthenticated && nextProps.user.isAuthenticated) {
        this.props.history.location.replace('/dashboard')
    }
  }

  /*static getDerivedStateFromProps(nextProps, prevState) {
    console.log('not even fired?')
    if (nextProps.user.isAuthenticated !== prevState.isAuthenticated) {
      return {
        isAuthenticated: '/dashboard'
      }
    }

    return null
  }*/

  handleSubmit() {
    const { email, password } = this.state
    this.props.loginUser(email, password)
  }

  render(){

    this.state.isAuthenticated && <Redirect to={'/dashboard'} />

    return(
      <LoginForm />
    )
  }
}

export default LoginFormContainer

1 个答案:

答案 0 :(得分:0)

this.state.isAuthenticated是表示身份验证状态的布尔值,在'/dashboard'中将其设置为getDerivedStateFromProps不会更改路由。您仍然需要致电this.props.history.replace('/dashboard')

您应该将componentWillReceiveProps更改为componentDidUpdate以进行路线更改操作。请注意,您应该使用this.props引用更新的道具,使用componentDidUpdate的第一个参数引用之前的道具。

成功登录后在loginUser中执行路由重定向可能更好一点,如果componentDidMount在本地缓存,则isAuthenticated