【问题标题】:Not waiting to get result from useDispatch() in react redux不等待从react redux中的useDispatch()获取结果
【发布时间】:2021-05-07 08:10:29
【问题描述】:

我在使用 useDispatch、useSelector 和 redux 的钩子时遇到了一些问题。 mapDispatchToProps、mapStateToProps 也有同样的问题。

我在下面附上了示例代码。基于该问题是.. 在按钮单击(saveSettings() 方法)上,当我在从另一个 dispatch(cn_saveData()) 调用获得成功结果后尝试使用 dispatch(cn_fetchData()) 调用操作方法时,它不会等待使用 useSelector 获取成功消息“cn_saveDataValue”。尝试使用异步等待。但它失败了。

const dispatch = useDispatch();
const cn_fetchData = (appId) => dispatch(_fetchcn_appValues(appId));
const cn_saveData = (appId, testData) => dispatch(_saveSettings(appId, testData));

const cn_saveDataValue = useSelector(state => state.AppReducer.cn_saveDataValue);
const cn_appValues = useSelector(state => state.AppReducer.appData);

const saveSettings = async () => {
    try {
        await cn_saveData(
            appData._id,
            testData,
        );
        // **Issue is here. Its not waiting to get cn_saveDataValue to true after updating to the database using "await cn_saveData"**
        if (cn_saveDataValue) {
            await cn_fetchData(appData._id); // Fetch updated data from the database using action, reducer
        }
    } catch {
        console.log("Err !! Please Try again !");
    }
}

我正在使用 action 和 reducer。设置减速器的响应。 if (cn_saveDataValue) 第一次在保存设置时为 false。所以等待 cn_fetchData(appData._id);方法不触发。

【问题讨论】:

    标签: reactjs redux react-hooks


    【解决方案1】:

    因为cn_saveData 是一个同步函数,而不是异步fn,所以它迫不及待地在更新后将cn_saveDataValue 设为true

    在这种情况下你应该使用useEffect

      useEffect(() => {
        if (cn_saveDataValue) {
          cn_fetchData(appData._id);
        }
      }
      }, [cn_saveDataValue]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-21
      • 2019-08-01
      • 2020-06-19
      • 1970-01-01
      • 2019-05-07
      • 2021-05-01
      • 2021-02-21
      • 2021-06-13
      相关资源
      最近更新 更多