简体   繁体   English

Reducer 被触发但订阅 function 未获取更改 [React-Redux]

[英]Reducer gets triggered but subscribe function not fetching the change [React-Redux]

reducer shows that I've received doc data from Firestore. reducer显示我已收到来自 Firestore 的doc数据。 docStore.subscribe is listening, but is not updating with latest doc data. docStore.subscribe正在监听,但没有更新最新的doc数据。

Expected outcome: upon page load, will get docId from URL, and query Firestore.预期结果:页面加载后,将从 URL 获取docId ,并查询 Firestore。 Upon receiving data, update the store, and subscribe to populate the view with doc information.收到数据后,更新存储,并subscribe以使用doc信息填充视图。

homepage.js主页.js

const Homepage = ({ docId }) => {

  const [doc, setdoc] = useState(false);

  console.log(docId); // <-- 123

  docStore.subscribe(() => {
    console.log('docStore state changed:', docStore.getState()); // <-- docStore state changed: undefined
    setdoc(docStore.getState());
  })  

  return (
    <div>
      <div>{docId}</div> {/* 123 */}
      <div>{doc.docName}</div> {/* blank */}
    </div>
  );
};

reducer.js减速器.js

export default function reducer(state = {}, action) {
  switch (action.type) {

    case docTypes.LOAD_DOC_PAGE:
      firebase.firestore().collection("docs")
        .where('docId', '==', action.payload.docId.toLowerCase())
        .get()
        .then(function (data) {

          if (data.docs.length === 1) {
            state = data.docs[0].data();
          }

          console.log('gotten doc', state) // <-- gotten doc data

          return state;
        });
  }
}

Your reducer is very broken.你的减速机坏了。 Reducers must never make async calls! Reducers 绝不能进行异步调用! . . That API call needs to be moved somewhere else entirely, and then you should dispatch an action that will cause the reducer to run and calculate an updated state. API 调用需要完全移到其他地方,然后您应该调度一个动作,该动作将导致减速器运行并计算更新的 state。

Also, you generally shouldn't subscribe to the store yourself.此外,您通常不应该自己订阅商店。 Use the React-Redux connect and useSelector APIs to extract data needed by components from the store state.使用useSelector connect和使用选择器 API 从存储区 state 中提取组件所需的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM