Redux中发送异步请求获取数据
作者:
泡杯感冒灵 | 来源:发表于
2022-03-20 15:31 被阅读0次步骤
- 首先,引入axios,在生命周期函数componentDidMount中发送请求。
- 获取到数据后,通过store.dispatch派发一个action给store,store拿到这个action连同原先的数据,一起发给reducer。
- reducer里,深拷贝store传来的数据,然后改变拷贝对象的数据,再把这个拷贝对象返回给store
- store拿到这个拷贝对象,替换原来的数据
- 组件通过store.subscribe方法订阅了store的变化,这个时候执行传给subscribe的函数,通过setState更新组件的state。
import axios from 'axios';
componentDidMount(){
axios.get('/list.json').then((res)=>{
const data = res.data;
const action = initListAction(data);
store.dispatch(action);
})
}
// actionCreators.js
export const initListAction = (data) => ({
type: INIT_LIST_ACTION,
data
})
// reducer.js
if(action.type === INIT_LIST_ACTION){
const newState = JSON.parse(JSON.stringify(state));
newState.list = action.data;
return newState;
}
本文标题:Redux中发送异步请求获取数据
本文链接:https://www.haomeiwen.com/subject/exhndrtx.html
网友评论