我不明白如何从reducer商店获取更新的值。例如,我有一个React组件。在该组件中,经过一些动作(例如,单击按钮几下)后,我从减速器动作脚本(如this.props.PostSomethingToServer()
)中调用了该动作。然后,该操作将一些数据发送到节点快递服务器。服务器对数据进行一些更改,然后将响应发送到客户端存储缩减程序。如何从减速机商店获取更新的数据?我需要使用更新的值在此React组件中调用另一个函数。顺便说一下,我在React组件中使用了mapStateToProps
和export default connect()
。据我所知,mapStateToProps
和export default connect()
有助于在render()
之前从存储中获取数据。但是我仍然不知道如何在执行某些操作后如何从存储中获取更新的数据。几个代码:反应组件:
ChangeArrayData(){
let something = [];
// filling this array and modifying values
//then I call the action
this.props.postSomethingToServer(something);//something will be changed by server logic and will be returned with updated data by a response.
//then I wanna export the data to .excel, for example
this.ExportToExcel(); // here I have to get updated data from the reducer, but I don't have any information about changes in the reducer.
}
减速器动作:
export const postSomethingToServer= rankedElements => dispatch => {
axios
.post("/api/postData", elements)
.then(response => {
dispatch({
type: POST_SOMETHING_SUCCESSFUL,
status : "success",
payload: response.data
});
//... etc.
减速器:
const initialState = {
something: {},
status: "",
error : ""
};
export default function(state = initialState, action) {
switch (action.type) {
case POST_SOMETHING:
return {
...state,
status: action.status,
}
case POST_SOMETHING_SUCCESSFUL:
return {
...state,
status: action.status,
something: action.payload
}
case GET_ERRORS:
return {
...state,
status: action.status,
error: action.error
}
default:
return state;
}
}
分派操作后,减速器状态something
应具有所需的数据。假设您已在mapStateToProps
函数中映射了数据,则可以通过props
访问它。
ChangeArrayData() {
let something = [];
this.props.postSomethingToServer(something);
this.ExportToExcel();
console.log(this.props.somethingReducerState);
}
const mapStateToProps = (state) => ({
somethingReducerState: state.yourReducerName.something,
});