需要根据状态或演示组件的 props 调度一个 Action 。
const mapDispatchToProps = (dispatch) => {
return {
onClick: () => {
if (state.someValue || this.props.someValue){
dispatch({type: DO_SOMETHING})
}
}
}
}
这个 Action 应该被 redux-saga 拦截来执行一些远程获取任务,所以我不能将此条件移动到 reducer 中,例如:
const reducer = (state, action) => {
switch (action.type){
case DO_SOMETHING:
if(state.someValue){
return {...state, //do something}
//I need to fetch some api here, so this won't be a valid way
}
}
}
可以从 reducer 内部触发调度吗?这样新触发的调度就可以被 redux-saga 拦截。
最佳答案
无法从 reducer 中触发调度
如果检查状态必须由组件完成,则使用 third parameter of connect
, aka mergeProps :
const mapStateToProps = state => ({
someValue: // ...,
// ...
})
const mapDispatchToProps = dispatch => {
return {
onClick: () => dispatch({type: DO_SOMETHING}),
// ...
}
}
const mergeProps = (stateProps, dispatchProps, ownProps) => {
const onClick = () => {
if (stateProps.someValue) {
dispatchProps.onClick();
}
}
return ({
...stateProps,
...dispatchProps,
onClick
})
}
export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(MyComponent)
如果检查状态不需要成为组件的一部分,则检查 saga 任务中的状态:
组件:
const mapDispatchToProps = dispatch => {
return {
onClick: () => dispatch({type: MAYBE_DO_SOMETHING}),
// ...
}
}
传奇:
function* onMaybeDoSomething(action) {
const someValue = yield select(getSomeValue)
if (someValue) {
yield put({ type: DO_SOMETHING })
}
}
export default function* () {
takeLatest(MAYBE_DO_SOMETHING, onMaybeDoSomething)
}
关于reactjs - 如何从mapDispatchToProps内部访问状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53149856/