问题描述
我使用 redux 编写了一个容器组件,我的 mapDispatchToProps
实现看起来像这样
I have written a container component using redux and my implementation for mapDispatchToProps
looks like this
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onChange: (newValue) => {
dispatch(updateAttributeSelection('genre', newValue));
dispatch(getTableData(newValue, ownProps.currentYear));
}
}
}
问题是为了 getTableData 我需要一些其他组件的状态.如何在此方法中访问状态对象?
The problem is that in order to getTableData I need the state of some other components. How can I get access to the state object in this method?
推荐答案
你可以使用 redux-thunk 创建一个单独的 action creator 函数,它可以访问 getState
,而不是在 getState
中定义函数代码>mapDispatchToProps:
You can use redux-thunk to create a separate action creator function which has access to getState
, rather than defining the function inside mapDispatchToProps
:
function doTableActions(newValue, currentYear) {
return (dispatch, getState) => {
dispatch(updateAttributeSelection('genre', newValue));
let state = getState();
// do some logic based on state, and then:
dispatch(getTableData(newValue, currentYear));
}
}
let mapDispatchToProps = (dispatch, ownProps) => {
return {
onChange : (newValue) => {
dispatch(doTableActions(newValue, ownProps.currentYear))
}
}
}
有一些不同的方法来组织这些,但类似的方法应该可行.
Some varying ways to go about organizing those, but something like that ought to work.
这篇关于访问 mapDispatchToProps 方法内部的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!