[英]React/Redux firing action->render before update a store
A have a simply react/redux app. 有一个简单的react / redux应用程序。 I Fetch data from API async but component not waiting for data and firing render.
我从API异步获取数据,但组件未等待数据并触发渲染。
class RestaurantList extends React.Component {
componentWillMount() {
this.props.getRestaurantList();
}
render() {
console.log("render");
let {translation} = store.getState().app;
//------------I NEED DATA ON THIS LET (restaurantList)
let {restaurantList} = this.props.restaurants;
return (
<div>
<TableContainer data={restaurantList}/>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
restaurants: state.restaurants
};
};
const mapDispatchToProps = (dispatch) => {
return {
getRestaurantList() {
dispatch(ACTIONS.getRestaurantList());
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(RestaurantList);
On my action i fetching data using axios :
在我的行动中,我使用axios获取数据:
export function getRestaurantList() {
console.log("action");
return dispatch => {
axios({
method: "GET",
url: URLS.BASE_URL + URLS.URL_RESTAURANT_LIST
}).then((response) => {
console.log(response);
dispatch({
type: CONST.GET_RESTAURANT_LIST,
payload: response.data
})
})
}
}
And my component fired method ComponenWillMount after that render () and next store which update store and set good data to my variable. 然后,我的组件在该render()和下一个存储区之后触发了方法ComponenWillMount,该存储区将更新存储区并为我的变量设置良好的数据。 Maybe u give me advice how to do that to have on my render my fetching data because now on my table I transfer undefined on start.
也许您会给我一些建议,以便在呈现获取的数据时进行渲染,因为现在在我的表上,我在开始时传输未定义的内容。 Maybe you give me an example to using another framework like redux-saga or other.
也许您给我一个使用redux-saga或其他框架的示例。
You could try conditionally rendering your TableContainer component so the table will only be rendered once there is data available: 您可以尝试有条件地呈现TableContainer组件,以便仅在有可用数据时才呈现表:
renderTable() {
let { restaurantList } = this.props.restaurants
if (restaurantList) {
return <TableContainer data={ restaurantList } />
} else {
return <div></div>
}
}
render() {
return (
<div>
{ this.renderTable() }
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.