【问题标题】:Using axios with React and Redux将 axios 与 React 和 Redux 一起使用
【发布时间】:2020-06-19 14:20:19
【问题描述】:

我想从 API 中获取数据并将它们放入我的documents,我知道该怎么做,但我不知道正确的方法。我在一些教程中看到说我们必须在中间件中进行每个 API 调用,但我找不到任何示例。

我的代码:

listReducer.js

const initialState = {
  documents: []
}

export default function documents(state = initialState, action) {
  switch (action.type) {
    case 'LOAD_DOCS':
      //set documents = response from api
    default:
      return state
  }
}

listAction.js

export function loadDocs(offset, range) {
  return {
    type: 'LOAD_DOCS',
    offset,
    range
  }
}

store.js

import { createStore } from 'redux'

import reducers from './reducers'
const store = createStore(reducers)

export default store

【问题讨论】:

  • 我认为中间件是指使用redux-thunk、redux sagas 或 redux-observables 之类的东西来允许您调度“异步”操作。
  • 现在我明白了,谢谢!

标签: javascript node.js reactjs redux


【解决方案1】:

您好,您可以使用 redux 中间件“Redux-thunk”创建一个 thunk。 thunk 基本上是一个函数,您可以在其中进行 API 调用,在从服务器获取数据后,您可以调度一个操作以将数据设置到减速器中。 您将在您将创建的 thunk 中获取调度函数。

所以不是直接调用 dispatch 而是调用 thunk 函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2017-12-09
    • 2018-12-05
    • 2018-06-10
    • 1970-01-01
    • 2019-05-16
    • 2016-08-07
    相关资源
    最近更新 更多