【问题标题】:Component is not updating when redux state changes [duplicate]redux 状态更改时组件未更新[重复]
【发布时间】:2023-04-02 00:12:01
【问题描述】:

我有一个带有选择器的反应组件,它从 firebase 数据库中获取一些状态。但是,在我的组件的useEffect 中,将此状态作为依赖项,即使 Redux 开发工具显示状态已更新,它也只会返回一个空数组。控制台还会打印空数组,但是当我展开它时,数组会更新。会发生什么?

我的组件的最小版本:

const PatientsPage = () => {
  const dispatch = useDispatch();
  const invitedPatients = useSelector((state) => state.invitations.invitedPatients);

  useEffect(() => {
    console.log("in use effect invited patients", invitedPatients);
    // console prints empty array but when I expand it
    // it is populated yet this function isn't triggered again to set the new value for rendering
  }, [invitedPatients]);

  useEffect(() => {
    // this dispatches the invitedPatients action
    dispatch(getInvitations(firebase.auth().currentUser.uid));
  }, []);

}

我不知道问题是什么。如果需要,我可以发布我的动作和减速器功能。请提供一些关于如何诊断问题的指导。谢谢

编辑: 这是行动

export const getInvitations = (doctorId) => {
  const invitationObjects = [];
  const invitedPatients = [];
  return async (dispatch, getState, getFirebase) => {

     ...code to populate my invitationsObjects

      invitationObjects.forEach(async (invitationObject) => {
        const invitedPatient = await getPatient(invitationObject.patientId);
        invitedPatients.push(invitedPatient);
      });

      dispatch({
        type: GET_INVITATIONS_SUCCESS,
        payload: invitedPatients,
      });
    } catch (error) {
      ...
    }
  };
};

还有减速器

const initialState = {
  invitedPatients: null,
  sending: false,
};

export default function invitationsReducer(state = initialState, action) {
  switch (action.type) {
    case "GET_INVITATIONS_SUCCESS":
      return {
        ...state,
        invitedPatients: action.payload,
      };
    
    default:
      return { ...state };
  }
}

这是 getPatient 函数:

export const getPatient = async (patientId) => {
  try {
    const documentSnapshot = await firestore.collection("patients").doc(patientId).get();
    console.log("getPatient -> documentSnapshot", documentSnapshot.data())
    return documentSnapshot.data();
  } catch(error) {
    console.log(error);
  }
}

【问题讨论】:

  • 我们需要查看您的getInvitations 操作和您的reducer 以了解它在做什么。如果您更改数组而不是将其设置为新值,则数组的对象引用将是相同的,并且不会被检测为更改。
  • 您可能正在改变您的操作中的状态,请您展示您的操作吗?
  • @Jacob 我已经添加了我的动作和减速器
  • @SaherElgendy 我已经添加了动作和减速器

标签: javascript reactjs redux react-hooks use-effect


【解决方案1】:

问题是您不能在 forEach 循环中使用异步函数。我将其更改为使用正常的循环表示法并且它起作用了。

【讨论】:

  • 你不需要串行获取,如果你查看this answer,你可以并行获取数据。
猜你喜欢
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 2019-08-31
  • 2018-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多