需要根据国家或娱乐场所的道具来派遣行动。
const mapDispatchToProps = (dispatch) => {
return {
onClick: () => {
if (state.someValue || this.props.someValue){
dispatch({type: DO_SOMETHING})
}
}
}
}
并且该动作应该被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
}
}
}
可以从减速器内部发出调度吗?这样新的解雇调度可以被redux-saga拦截。
答案 0 :(得分:0)
无法从减速器中发出调度
如果必须由组件完成检查状态,请使用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)
如果检查状态不需要成为组件的一部分,则在一个传奇任务中检查状态:
组件:
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)
}