【发布时间】: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