使用 redux 工具包调度的竞争条件

Race condition using redux toolkit dispatch

提问人:deadant88 提问时间:11/7/2023 更新时间:11/7/2023 访问量:26

问:

我正在尝试根据登录用户是否已完成载入有条件地导航。在下面的函数中,逻辑似乎没有等待调度足够长的时间(或根本没有等待),从而导致导致并触发错误的条件导航逻辑的争用条件。currentStudent.onboardingCompletedundefined

我想知道如何更好地构建事物以使其更稳定?

const StudentLoginForm = () => {
  const [spellcastUsername, setSpellcastUsername] = useState('');
  const navigate = useNavigate();
  const dispatch = useDispatch<AppDispatch>();
  const [isLoading, setIsLoading] = useState(false);
  const currentStudent = useSelector(
    (state: RootState) => state.selectedStudent,
  );

  const handleSubmit = async (spellcastUsername: string) => {
    setIsLoading(true); // Start loading

    try {
      const isStudentAuthenticated = await api.dbAuthenticateStudent(
        spellcastUsername,
      );

      if (isStudentAuthenticated) {
        preloadPhonemeAudio();

        await dispatch(
          fetchStudentAndCreateSessionThunk(isStudentAuthenticated.id),
        );

        if (currentStudent?.onboardingCompleted === true) {
          navigate(`/cardgame/${isStudentAuthenticated.id}`);
        } else {
          navigate(`/profile/${isStudentAuthenticated.id}`);
        }
      } else {
        alert('No User');
      }
    } catch (error) {
      console.error('Error during form submission:', error);
      alert('An error occurred. Please try again.');
    } finally {
      setIsLoading(false);
    }
  };
[...]

这是砰的一声:

export const fetchStudentAndCreateSessionThunk = createAsyncThunk(
  'session/fetchAndCreate',
  async (studentId: string, { dispatch, getState }) => {
    await dispatch(fetchStudentByIdThunk(studentId));
    const state = getState() as RootState;
    const studentNode = state.selectedStudent;
    if (studentNode && studentNode.id) {
      dispatch(setSelectedStudent(studentNode));
      dispatch(createNewSessionThunk(studentNode.id));
    }
  },
);

reactjs 异步 redux redux-toolkit redux-thunk

评论

0赞 Krzysztof Krzeszewski 11/7/2023
这回答了你的问题吗?调度完全完成后如何访问 redux 状态?
0赞 Dushan Ranasinghage 11/8/2023
我认为这也可以回答他的问题。需要从 useEffect 访问该数据。否则,它将访问当前状态,由于 redux 的异步行为,该状态可能为 null。

答: 暂无答案