我尝试在我学习的 react、redux 项目中使用 axom 处理 ajax 数据,但我不知道如何分派(dispatch)一个 Action 并设置组件内的状态
在组件中将挂载
componentWillMount(){
this.props.actions.addPerson();
}
商店
import { createStore, applyMiddleware } from "redux";
import rootReducer from "../reducers";
import thunk from "redux-thunk";
export default function configureStore() {
return createStore(rootReducer, applyMiddleware(thunk));
}
在行动中:
import * as types from "./action-types";
import axios from "axios";
export const addPerson = person => {
var response = [];
axios
.get(`&&&&&&&&&&&`)
.then(res => {
response = res.data;
return {
type: types.ADD_PERSON,
response
};
});
};
在 reducer 中
import * as types from "../actions/action-types";
export default (state = [], action) => {
console.log("action======>", action);
switch (action.type) {
case types.ADD_PERSON:
console.log("here in action", action);
return [...state, action.person];
default:
return state;
}
};
我得到的是 Actions must be plain objects。使用自定义中间件进行异步操作。
最佳答案
您应该为异步函数使用分派(dispatch)。查看 redux-thunk 的文档:https://github.com/gaearon/redux-thunk
在行动中:
import * as types from "./action-types";
import axios from "axios";
export const startAddPerson = person => {
return (dispatch) => {
return axios
.get(`https://599be4213a19ba0011949c7b.mockapi.io/cart/Cart`)
.then(res => {
dispatch(addPersons(res.data));
});
}
};
export const addPersons = personList => {
return {
type: types.ADD_PERSON,
personList
};
}
在 PersonComponent 中:
class Person extends Component {
constructor(props){
super(props);
}
componentWillMount() {
this.props.dispatch(startAddPerson())
}
render() {
return (
<div>
<h1>Person List</h1>
</div>
);
}
}
export default Redux.connect()(Person);
关于javascript - React Redux - 操作必须是普通对象。使用自定义中间件进行异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45825774/