如何从 axios.get 获取请求数据到 Redux store
How to get request data from axios.get to Redux 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'},
],
};
有什么方法吗?
在reducer里面放一个case in switch say...
case FETCH_DATA: {
return {...state, data: action.payload}
}
现在你已经准备好了 reducer 代码。在 then 块内调度操作 {type:FETCH_DATA, payload:response.data}
.then(response => {
this.setState({result: response.data});
})
你需要使用中间件来处理这种类型的 redux 副作用。您可以使用
redux-thunk or redux-saga
redux-thunk 文档解释 Why Do I Need This
Thunks are the recommended middleware for basic Redux side effects logic, including complex synchronous logic that needs access to the store, and simple async logic like AJAX requests.
您也可以使用 redux-saga 来完成类似的任务。
我是 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'},
],
};
有什么方法吗?
在reducer里面放一个case in switch say...
case FETCH_DATA: {
return {...state, data: action.payload}
}
现在你已经准备好了 reducer 代码。在 then 块内调度操作 {type:FETCH_DATA, payload:response.data}
.then(response => {
this.setState({result: response.data});
})
你需要使用中间件来处理这种类型的 redux 副作用。您可以使用 redux-thunk or redux-saga
redux-thunk 文档解释 Why Do I Need This
Thunks are the recommended middleware for basic Redux side effects logic, including complex synchronous logic that needs access to the store, and simple async logic like AJAX requests.
您也可以使用 redux-saga 来完成类似的任务。