【问题标题】:useEffect not firing when state is updated状态更新时不会触发useEffect
【发布时间】:2021-07-03 12:47:12
【问题描述】:

我有一个 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 缺少 isPCCIntegrated 的标志为 false 并且它停止了我的功能。

【问题讨论】:

  • 变量currentUserprops.currentUser 都不是您显示的代码中的状态。
  • props.currentUser 的值来自于 mapStateToProps。我刚刚加进去了。

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


【解决方案1】:

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

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

useEffect(() => {

some api calls...

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

【讨论】:

  • 这个解决方案是有道理的,但由于某种原因,这个修复程序无法编译,我收到新的 currentUser 错误。说Object(...) is not a function。正在寻找解决方案并找到 this 但不确定我是否理解解决方案。
  • 但是现在我阅读了更多关于它的内容,在 mapStateToProps 上使用 useSelector 挂钩有什么好处?
  • 您需要删除或注释掉some API calls...如果您在代码中的某处使用“扩展运算符”,请确保您的 Babel 配置支持它。
猜你喜欢
  • 2023-01-26
  • 1970-01-01
  • 2022-01-08
  • 2020-01-25
  • 2019-05-07
  • 2021-05-05
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多