在 Redux 中,如何让状态生效?

Vis*_*ani 3 react-native redux react-redux

在下面的示例中,从 firebase 获取数据后,我想添加 redux 存储中已经存在的用户对象并将其附加到所有消息对象中。请求你帮忙。

问题:

  1. 这是在动作创建者中访问状态的好方法吗?如果是,如何?
  2. 如果没有,有哪些替代方案?
db.collection(`messages/${documentId}/chat`)
  .get()
  .then(snapshot => {
    const messages = [];
    snapshot.docs.forEach(doc => {
    console.log("message", doc.id, doc.data());
    messages.push({
      id: doc.id,
      from: doc.data().from,
      to: doc.data().to,   
      text: doc.data().text,
      timestamp: doc.data().timestamp.seconds * 1000
    });
  });
  dispatch({ type: GET_CHAT, payload: messages });
});
Run Code Online (Sandbox Code Playgroud)

Hen*_*hli 9

如果您使用 Redux Thunk 中间件,您可以简单地这样做:

const myAction = () => async (dispatch, getState) => {
  const { field1, field2 } = getState().myReducer;
};
Run Code Online (Sandbox Code Playgroud)