首页 > 解决方案 > React 组件事件处理函数没有收到来自 Redux Store 的最新值

问题描述

我正在开发一个简单的应用程序作为我的副项目,只是为了更多地了解 React 和 Redux。我在调用异步操作创建器时发现了一个问题,它更新了减速器中的值,但是当我尝试访问组件事件处理程序函数中的值时,它仍然具有旧值。

这是我的动作创建者:

export const assignUsername = username => async dispatch => {
  dispatch({type: types.ASSIGN_USERNAME_REQUEST})

  await axios({
    method: "PUT",
    url: "/v1/user/username",
    data: {
      username: username
    }
  })
  .then(response => {
    if(response.data && response.data.success){
      dispatch({
        type: types.ASSIGN_USERNAME_SUCCESS,
        payload: response.data.result
      })
    }else{
      dispatch({type: types.ASSIGN_USERNAME_FAILED})
      dispatch(httpPopUpError(response.status, response.data.message))
    }
  })
}

这是减速器:

var initialState = {
  loading: false,
  result: null,
  error: false
};

function AuthReducer(state = initialState, action) {
  switch (action.type) {
    case types.ASSIGN_USERNAME_REQUEST:
      return {
        ...state,
        loading: true,
        error: false
      }
    case types.ASSIGN_USERNAME_FAILED:
      return {
        ...state,
        loading: false,
        error: true
      }
    case types.ASSIGN_USERNAME_SUCCESS:
      return {
        ...state,
        loading: false,
        result: action.payload,
        error: false
      }
    default:
      return state;
  }
}

这是调用动作创建者并访问商店的事件处理函数:

  handleAssignUsername = (e) => {
    e.preventDefault();

    formValidator(this.state.form)
      .then(validatedForm => {
        this.setState({
          ...this.state,
          form: validatedForm
        }, () => {
          this.props.assignUsername(this.state.form.username.value)
          .then(() => {
            if(!this.props.AuthReducer.error) {
              this.props.history.push("/")
            }
          })
        })
      })
      .catch(errorForm => {
        this.setState({
          ...this.state,
          form: errorForm
        })
      })
  }

正如您在上面看到的,我访问“this.props.AuthReducer.error” tp 确定它是否有错误然后决定重定向。但是,尽管在 Redux Devtools 中我看到它已经变为true,但错误值仍然是false

如果有人能提供帮助,我真的很感激,或者如果我的方法不合适,我可能会建议一种更优雅的方法。谢谢你。

注意:我在我的另一个项目中尝试了类似的方法,并且效果很好。这就是让我感到困惑的原因,因为有时它有效,有时则无效。

编辑: 我尝试了Hemanath的建议,但是当我在控制台记录错误时,即使错误在 Store 中变为true ,它仍然具有相同的值。

 componentDidUpdate(prevProps){
  console.log(prevProps.AuthReducer.error, "PREV");
  console.log(this.props.AuthReducer.error, "NOW");
  if(prevProps.AuthReducer.error === false && this.props.AuthReducer.error === true){
    this.props.history.push("/");
  }
}

console.log 的截图 关于在 render 方法中重定向,恐怕这不是一个好方法,因为错误的默认值为FALSE,如果我这样做,它总是会重定向。

我想先执行 AJAX 请求,然后如果错误仍然是错误的,则重定向。

标签: javascriptreactjsreduxredux-thunk

解决方案


使用componentDidUpdate生命周期方法来观察this.props.AuthReducer.error值的变化并根据新值从那里重定向,

componentDidUpdate(prevProps){
  if(prevProps.AuthReducer.error === false && this.props.AuthReducer.error === true){
    this.props.history.push("/");
  }
}

或者按照评论中的建议,您可以使用方法中的组件Redirect进行重定向,就像这样react-routerrender

render() {
    const { AuthReducer } = this.props;
    if (AuthReducer && AuthReducer.loading === false && AuthReducer.error === true) {
      return <Redirect to='/' />;
    }
    return (
      <div>....</div>
    );
  }

推荐阅读