繁体   English   中英

如何在 React-redux 中状态更新后刷新组件

[英]How to refresh component after state update in React-redux

我正在使用带有 thunk 的 React-Redux。 我的动作生成器通过 thunk 启动对 API 的调用,然后按预期接收状态中的数据。 我在 useEffect 函数中调用动作生成器,一旦我从 API 获得数据,我想更新我作为视图的饼图。 但我不知道该怎么做。 由于我在API调用成功并且数据处于状态后将数据从状态加载到数组(数据源到饼图)。

请建议下面是有问题的代码。

  useEffect(()=> {
    const reqData = {
      "customerId" : "5",
      "month" : "12",
      "year" : "2019"
    };
    initCategoryExpInfo(reqData,()=>{
      initPieChartData();
    });
  },[navigation,initCategoryExpInfo]);


  ......

  const initPieChartData = () => {
  for(i = 0;i < categoryExpenses.length;i++) {
    var item = categoryExpenses[i];
    series.push(item.expenseAmount);
  }

  };

我已经通过 redux 函数 connect 和 props 将动作连接到状态,我猜这工作正常,因为我在商店中获取数据就好了,下面是动作生成器的样子

export const performGetAllExpensesByCat = (reqData,callback) => (dispatch, _, {api}) => {
  return getAllExpensesByCat(api)(reqData).then(res => {
    console.log(res.data);
    dispatch(setExpensesByCat(res));
    callback();
  });
};

唯一的问题是如何刷新组件以便我的饼图得到更新

<PieChart
    chart_wh={chart_wh}
    series={series}
    sliceColor={sliceColor}
    doughnut={true}
    coverRadius={0.7}
    coverFill={'#FFF'}
/>

你可以这样做:

  1. 发送 thunk-api 调用。
  2. 成功响应后,调度另一个操作,使用 api 调用的响应更新 redux 存储。
  3. 在您的组件中,连接到步骤 2 中的 redux 状态。

因此,每当您调度另一个 thunk-api 调用时,redux 存储将在成功响应时更新,进而更新您的组件。

希望这是有道理的。

例如

useEffect(()=>{
    // thunk action dispatcher for the api call on component mount
    fetchDataFromApiCall()
}, [])
// In the action generator file
fetchDataFromApiCall() => {
    return async (dispatch, getState) => {
        await actualApiCall().then((response)=>{
            dispatch(updateReduxState(response))
        }
// In your component
mapStateToProps = (state) => ({
    data: getDataFromReduxState(state)
})

现在,你有data做任何你想做的事情。 此外,只要data发生变化,组件就会重新渲染,所以不用担心。

暂无
暂无

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

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