【问题标题】:How to get request data from axios.get to Redux store如何从 axios.get 获取请求数据到 Redux 存储
【发布时间】:2018-12-11 11:14:57
【问题描述】:

我是 Redux 的新手。有人可以解释一下,我如何从 Get 获取请求数据

componentDidMount() {
        axios.get('/api/v3/products', {
            params: {
                pageNumber: 1,
                pageSize: 500,
            }
        })
            .then(response => {
                this.setState({result: response.data});
            })
            .catch(function (error) {
                console.log('error TestMethod', error);
            })
            .then(function () {
                // always executed
            });
    }

并将其放在 Redux 中的 store 中

const initState = {
    products: [
        {id: 1, title: 'first'},
        {id: 2, title: 'second'},
        {id: 3, title: 'third'},
        {id: 4, title: 'fourth'},
        {id: 5, title: 'fifth'},
    ],
};

有什么方法吗?

【问题讨论】:

  • 我有带有 initState 的 rootReducer,我是否应该将 Get 请求中的代码放在里面?
  • 我知道如何将它放在状态中,但是我如何从 Get 中抓取它并将其放置到存储中,这非常困难

标签: javascript reactjs redux get store


【解决方案1】:

在reducer里面放一个case在switch说...

case FETCH_DATA: { 
  return {...state, data: action.payload}
}

现在你已经有了 reducer 代码。在 then 块调度动作 {type:FETCH_DATA, payload:response.data}

.then(response => {
            this.setState({result: response.data});
        })

【讨论】:

  • 你的意思是我应该把get请求代码放在reducer里面?
  • 所以我需要使用这个获取请求,如果我的数组名为“产品”,我应该将结果更改为产品吗?就这样?
  • 是的,正确的结果将是产品。所以我需要使用这个获取请求吗? (这取决于 api/服务)。希望我回答了这两个问题。
【解决方案2】:

您需要使用中间件来处理这种类型的 redux 副作用。你可以使用 redux-thunkredux-saga

redux-thunk 文档解释 Why Do I Need This

Thunk 是基本 Redux 副作用逻辑的推荐中间件,包括需要访问存储的复杂同步逻辑,以及 AJAX 请求等简单异步逻辑。

你也可以使用 redux-saga 来完成类似的任务。

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2021-05-03
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多