我有一个操作可以返回一系列用户。
此操作位于componentDidMount函数内部,并返回我想要的数据,但是当我尝试访问已更新的this.props.getUsuarios的状态时,我无法实现。
运行GET_USUARIO操作时,应该更新usuarios的Array不是吗?因为我想在地图函数中使用新状态,但是它总是返回初始状态。
RootReducer
import { combineReducers } from "redux";
import Usuarios from "./../components/PaginationReducer";
const rootReducer = combineReducers({
usuarios: Usuarios
});
export default rootReducer;
操作:
export const getUsuarios = () => {
const request = axios.get(configs.BASE_URL + "users");
return {
type: "GET_USUARIOS",
payload: request
};
};
减速器:
const INITIAL_STATE = { usuarios: [] };
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case "GET_USUARIOS":
console.log(action.payload.data);
return { ...state, usuarios: action.payload.data };
case "MAKE_PAGINATION":
return { ...state, usuarios: action.payload.data };
default:
return state;
}
};
与Redux反应组件连接:
class Table extends React.Component {
componentDidMount() {
console.log(this.props.usuarios); //not updating the state
console.log(this.props.getUsuarios); //bring the array result
}
}
const mapStateToProps = state => ({
usuarios: state.usuarios
});
const mapDispatchToProps = dispatch =>
bindActionCreators({ PaginationAction, getUsuarios }, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(Table);