我有 2 条路线 /dashboard
和 /battery
,在 /dashboard
上我在 componentWillMount()
上调用我的 API code>,然后一旦我使用 redux 收到响应,我就会执行 componentWillReceiveProps()
来更新我的状态及其工作正常,但是如果我使用react-router-dom导航到/battery 然后想要来回到/dashboard,如何防止 API 调用,因为数据已经存在于 redux-store 中。
// To go to the /battery I do
history.push('/main/battery')
// To go to the /dashboard I do
history.push('/main/dashboard')
// Dashboard Component (/main/dashboard)
componentWillMount() {
this._callAPI()
}
componentWillReceiveProps(nextProps) {
// update state
}
最佳答案
一个可能的解决方案是,在 Action 创建器中,您可以使用 getState()
获取当前的 redux 状态。只需在 api 调用之前检查您的 redux 存储是否为空或未设置。
这是执行此检查的操作创建者的示例:
requestList: () => {
return (dispatch, getState) => {
if (getState().list === null) {
/* API CALL HERE*/
}
}
}
关于reactjs - 如果数据存在于 redux 存储中,则阻止 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55515959/