reactjs - 如果数据存在于 redux 存储中,则阻止 API 调用

标签 reactjs redux

我有 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/

相关文章:

java - 使用 flatMap 连接 Observables (RxJava )

javascript - react 路由器 : TypeError Cannot read properties of undefined (reading 'originalPositionFor' )

javascript - 如何在 Firebase 帐户中显示用户名

reactjs - 在 React+Redux 应用程序中将网络调用放在哪里

react-native - redux 中的 action、reducer 和 store 有什么区别?

css - 如何从一个小部分的 material-ui AppBar 中删除高程(框阴影)?

javascript - 遍历数组并动态发送http请求

react-native - I18Next - 等待使用本地数据设置 Redux 存储

javascript - 当使用 redux saga 和 React 时,状态如何在 sagas.js 中获取

redux - Slice 在 reducer 中的 State 自引用