首页 > 解决方案 > 状态更新时不会触发useEffect

问题描述

我有一个 useEffect 钩子,它应该在 currentUser 的状态变化时触发。然而,它似乎会触发一次或两次,但在刷新时 currentUser 值变为 null 并且只有有时 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 缺少标志为isPCCIntegratedfalse 并且它停止了我的功能。

标签: reactjsasynchronousreact-hooksstateuse-effect

解决方案


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

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

useEffect(() => {

some api calls...

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

推荐阅读