【问题标题】:React - useSelector not updated after dispatchReact - 调度后未更新useSelector
【发布时间】:2020-08-01 00:14:29
【问题描述】:

我有一个方法可以使用来自useSelector 的值,而另一个调度会更新我来自useSelector 的值,但是,例如,调度后该值似乎没有得到更新

const userProfile = (props) => {
  const hasValidationError = useSelector(state => {
     state.hasValidationError;
  }

  const dispatch = useDispatch():

  const updateProfile = async (userId) => {
     dispatch(startValidation());    // <-- this would change the hasValidationError in state
     if (hasValidationError) {
        console.log('should not update user');
        await updateUser(userId);
        dispatch(showSuccessMsg());
     } else {
        conosole.log('can update user');
     }
  }
}

hasValidationError 将始终为 false,即使值确实从状态更改,我如何才能在 dispatch(startValidation()) 之后立即获得更新的值?

我还尝试了一些不同的方法,例如使用 useState() 和 useEffect() 创建一个本地状态值来监控我的全局状态

const [canUpdateUser, setCanUpdateUser] = useState(false);

useEffect(() => {
    console.log('useEffect hasValidationError :>> ', hasValidationError);
    setCanUpdateUser(!hasValidationError);
  }, [hasValidationError]);

然后在 updateProfile (if (canUpdateUser)) 中使用 canUpdateUser 作为我的条件标志,但是,这似乎只在第一次验证触发时才有效,但在那之后,canUpdateUser 值始终是我的旧值再次更新个人资料... 我该如何解决这个问题?有什么方法可以确保在某些调度触发后从全局状态获取更新的值?

【问题讨论】:

    标签: javascript reactjs react-redux react-hooks


    【解决方案1】:

    您是否可以尝试使用稍微不同的方法(结合两者),因为您似乎想监听 hasValidationError 的变化,使用依赖于该变量的 useEffect 可能会解决您的问题。

    const userProfile = (props) => {
      const { hasValidationError } = useSelector(state => state);
      const dispatch = useDispatch():
    
      const [userId, setUserId] = useState();
    
      const updateProfile = async (userId) => {
         dispatch(startValidation());
         setUserId(userId);
      };
    
      useEffect(() => {
        if (hasValidationError) {
            console.log('should not update user');
            await updateUser(userId);
            dispatch(showSuccessMsg());
         } else {
            conosole.log('can update user');
         }
      }, [hasValidationError]);
    }
    

    【讨论】:

    • 非常感谢您的想法!不幸的是,当组件挂载时,这可能不起作用,因为当监控的hasValidationError 为真时触发 useEffect,它总是会尝试执行 useEffect 和 updateUser....
    • 另外,如果hasValidationError的值没有改变,那么useEffect不会被触发,这意味着如果没有验证错误,用户点击保存并且没有触发updateUser...
    猜你喜欢
    • 2021-10-15
    • 1970-01-01
    • 2023-03-10
    • 2022-01-24
    • 2020-09-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多