如何将请求数据从axios.get获取到Redux存储

时间:2018-12-11 11:14:58

标签: javascript reactjs redux get store

我是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中

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

有什么方法吗?

2 个答案:

答案 0 :(得分:1)

在减速器内放一个盒子,说...

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

现在您已安装了减速器代码。然后在内部阻止调度动作{type:FETCH_DATA,payload:response.data}

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

答案 1 :(得分:1)

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

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

  

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

您还可以使用redux-saga执行类似的任务。