[英]How to refresh component after state update in React-redux
I am using React-Redux with a thunk.我正在使用带有 thunk 的 React-Redux。 My action generator initiates a call to API and via thunk and then receives the data in state as expected.
我的动作生成器通过 thunk 启动对 API 的调用,然后按预期接收状态中的数据。 I call the action generator in useEffect function, once I have the data from API I want to update a piechart that I have as a view.
我在 useEffect 函数中调用动作生成器,一旦我从 API 获得数据,我想更新我作为视图的饼图。 But I am not able to figure out how to do it.
但我不知道该怎么做。 Since I load the data from state to the array (data source to a pie chart) after API call is successful and data is in the state.
由于我在API调用成功并且数据处于状态后将数据从状态加载到数组(数据源到饼图)。
Kindly suggest below is the code in question.请建议下面是有问题的代码。
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);
}
};
I have connected actions through redux function connect and props to state as well which I guess is working fine as I get the data in the store just fine, below is how the action generator looks like我已经通过 redux 函数 connect 和 props 将动作连接到状态,我猜这工作正常,因为我在商店中获取数据就好了,下面是动作生成器的样子
export const performGetAllExpensesByCat = (reqData,callback) => (dispatch, _, {api}) => {
return getAllExpensesByCat(api)(reqData).then(res => {
console.log(res.data);
dispatch(setExpensesByCat(res));
callback();
});
};
The only question is how to refresh the component so that my piechart gets updated唯一的问题是如何刷新组件以便我的饼图得到更新
<PieChart
chart_wh={chart_wh}
series={series}
sliceColor={sliceColor}
doughnut={true}
coverRadius={0.7}
coverFill={'#FFF'}
/>
You can do this:你可以这样做:
As such, whenever you dispatch another thunk-api call, the redux store will be updated on successful response, which in turn, will update your component.因此,每当您调度另一个 thunk-api 调用时,redux 存储将在成功响应时更新,进而更新您的组件。
Hope this makes sense.希望这是有道理的。
eg例如
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)
})
Now, you have the data
to do whatever you want to do.现在,你有
data
做任何你想做的事情。 Also, the component will be re-rendered whenever the data
changes, so no worries there.此外,只要
data
发生变化,组件就会重新渲染,所以不用担心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.