我在redux存储区和action + reducer中具有状态 nextBoxID ,该状态在按下按钮时会更新boxID。
问题是商店在按按钮时会按预期进行更新,但是从状态使用 nextBoxID 的功能不会更新。
const getNewBoxDispatch = (dispatch) => {
/*
Inner function used as onPress in a Button.
State is updated to the next ID, but the nextBoxID parameter doesn't update.
*/
const newBoxDispatch = (nextBoxID) => () => {
dispatch(addNewBox(nextBoxID))
dispatch(updateToNextID());
console.log('In newBoxDispatch: \n')
console.log('nextBoxID - ' + nextBoxID + ' (Initial boxID is 0)')
};
return newBoxDispatch;
}
const mapStateToProps = (state) => ({
newBoxID: state.nextBoxID,
})
const mapDispatchToProps = (dispatch) => ({
addNewBoxDispatch: getNewBoxDispatch(dispatch)
})
const mergeProps = (stateProps, dispatchProps, ownProps) => {
const newBoxID = stateProps.newBoxID;
console.log('In mergeProps: \n')
console.log('newBoxID - ' + newBoxID)
const addNewExperiment = dispatchProps.addNewBoxDispatch(newBoxID);
return({
...stateProps,
...dispatchProps,
...ownProps,
addNewExperiment
})
}
export default connect(
mapStateToProps,
mapDispatchToProps,
mergeProps
)(Home)
按下按钮后,商店将使用 newBoxID 更新,但 newBoxDispatch 的 nextBoxID 参数不会更新。>
例如,我们可以得到以下输出:
In mergeProps:
newBoxID - 4
In newBoxDispatch:
nextBoxID - 0 (Initial boxID is 0)
发生了什么事?
答案 0 :(得分:1)
您实际上很少需要使用mergeProps
。此外,您当前的代码通常看起来很奇怪。
如果您将逻辑编写为thunk,然后在组件调用它时将ID作为参数传递,或者从thunk本身的存储中读取值,则要简单得多。例子:
function addNewBoxFromParam(nextBoxID) {
return (dispatch, getState) => {
dispatch(addNewBox(nextBoxID))
dispatch(updateToNextID());
}
}
function addNewBoxFromState() {
return (dispatch, getState) => {
const {nextBoxID} = getState();
dispatch(addNewBox(nextBoxID))
dispatch(updateToNextID());
}
}
const mapState = (state) => ({
newBoxID: state.nextBoxID,
})
const actionCreators = {
addNewBoxFromParam,
addNewBoxFromState,
};
class MyComponent extends React.Component {
onAddFromParamClicked = () => {
this.props.addNewBoxFromParam(this.props.newBoxID);
}
render() {
return (
<div>
<button onClick={this.onAddFromParamClicked}>Add From Param</button>
<button onClick={this.props.addNewBoxFromState}>Add From State</button>
</div>
);
}
}
export default connect(mapState, actionCreators)(MyComponent);