React Redux 快速更新状态

React Redux Fast Update State

如何在发送后立即更新状态?

状态应该更新但没有。

应该改变什么?即使我们将在我们的代码中使用 then -> 即使那样我们也不会收到更新的状态,只有当我们从 .then((value) => { value.data }) 中获取值时,但我想从状态中获取数据

切片代码:

const authSlice = createSlice({
  name: 'auth',
  initialState: {
    user: {},
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(activateUser.fulfilled, (state, action) => {
        state.user = action.payload.userData
      })
  },
})

export const activateUser = createAsyncThunk('auth/activate', async (data) => {
  try {
    const userData = await authService.activateAccount(data)
    return { userData: userData.data.data }
  } catch (error) {
    const message =
      (error.response && error.response.data && error.response.data.message) ||
      error.message ||
      error.toString()
    return message
  }
})

const { reducer } = authSlice
export default reducer

组件:

function ActivateAccount() {
  const { user } = useSelector((state) => state.auth)
  const [code, setCode] = useState('')
  const dispatch = useDispatch()

  const activateUserAccount = () => {
    const data = {
      code: code?.value,
      userId: user?._id,
      email: user?.email || email?.value,
    }

    dispatch(activateUser(data))
    console.log('Why here value is not updated yet?', user)
    if (!user.activated) {
      setCode({
        ...code,
        isNotActivated: true,
      })
      return
    }

    return navigate('/on-board')
  }
 
}

为什么控制台日志值还没有更新?

应该改变什么?

有什么想法吗?

即使它是 Redux,它仍然需要在 React 组件生命周期的范围内工作。换句话说,需要更新状态并通知订阅者,然后 React 重新渲染更新后的状态。您当前正在记录 user 在当前渲染周期的函数范围内关闭的状态。无法记录任何后续渲染周期的状态。

不过您可以从异步操作开始链接,并检查任何已解析的值。

function ActivateAccount() {
  const { user } = useSelector((state) => state.auth);
  const [code, setCode] = useState('');
  const dispatch = useDispatch();

  const activateUserAccount = () => {
    const data = {
      code: code?.value,
      userId: user?._id,
      email: user?.email || email?.value,
    }

    dispatch(activateUser(data))
      .unwrap()
      .then(user => {
        console.log(user);
        if (!user.activated) {
          setCode(code => ({
            ...code,
            isNotActivated: true,
          }));
          return;
        }

        return navigate('/on-board');
      });
  }

  ...
}