【问题标题】:Prevent API call if data present in redux store如果数据存在于 redux 存储中,则阻止 API 调用
【发布时间】:2019-04-04 20:46:31
【问题描述】:

我有 2 条路由 /dashboard/battery,在 /dashboard 上我在 componentWillMount() 上调用我的 API,然后一旦我收到使用 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
}

【问题讨论】:

  • 在你的 componentWillMount 中向 Redux 发送一个动作,并在 reducer 中检查你的状态的正确部分是否存在。如果没有,请从 reducer 调用您的 api

标签: reactjs redux


【解决方案1】:

一种可能的解决方案,在您的动作创建器中,您可以使用getState() 获取当前的 redux 状态。只需在调用 api 之前检查您的 redux 存储是否为空或未设置。

这里是执行该检查的动作创建者的示例:

requestList: () => {
        return (dispatch, getState) => {
            if (getState().list === null) {
                /* API CALL HERE*/
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2018-02-26
    • 2018-07-02
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2022-12-05
    • 2018-08-13
    相关资源
    最近更新 更多