状态更新时 useEffect 不触发

时间:2021-04-07 16:51:39

标签: reactjs asynchronous react-hooks state use-effect

我有一个 useEffect 钩子,它应该在 currentUser 的状态改变时触发。然而,它似乎会触发一次或两次,但在刷新时 currentUser 值变为空,并且只有有时 useEffect 不会更新,因此我丢失了我的应用程序所依赖的数据。我的 api 调用中依赖于 currentUser 的数据最初显示但随后被丢弃。

const currentUser = props.currentUser || {};
const isPccIntegrated = isPCCUser(currentUser);


useEffect(() => {

some api calls...

loadEntries([]);
}, [props.currentUser]);

const loadEntries = async function(base, token){

let result = await api.UserRecords.chart(userID, token);
    if (result.pageToken) {
      // another page of entries exist, load the next page
      loadEntries(base.concat(result.items), result.pageToken);
    } else {
      // received last page of entries
      let allEntries = base.concat(result.items);

      if (isPccIntegrated) {
        try {
          // for PCC integrated patients, pull any progress note from PCC and add into the chart
          const pccNotes = await api.PCC.progressNotes(userID);
             ....
         }
       }....


const mapStateToProps = (state) => ({
  userID: state.router.location.pathname.split("/").pop(),
  currentUser: state.common.currentUser,
});

这表现为我的 loadEntries 函数崩溃,因为它依赖于 currentUser 对象。因此 currentUser 缺少 isPCCIntegrated 的标志为 false 并且它停止了我的功能。

1 个答案:

答案 0 :(得分:0)

代替 mapStateToProps 使用 react-redux 钩子 useSelector 来访问你的状态,然后将它放在 useEffect 依赖数组中代替 [props.currentUser]。更新后,您的 useEffect 将触发。

const currentUser = useSelector(state => state.common.currentUser)

useEffect(() => {

some api calls...

loadEntries([]);
}, [currentUser]);