如何从 mapDispatchToProps 内部访问状态 [英] How to access state from inside mapDispatchToProps
问题描述
需要根据 state 或presentaional 组件的props 调度一个动作.
Need to dispatch an action based on state or presentaional component's props.
const mapDispatchToProps = (dispatch) => {
return {
onClick: () => {
if (state.someValue || this.props.someValue){
dispatch({type: DO_SOMETHING})
}
}
}
}
而且这个动作应该被redux-saga拦截来做一些远程获取任务,所以我不能把这个条件移动到reducer中:
and this action is supposed to be intercepted by redux-saga to do some remote fetching tasks, so I can't move this condition into reducer like:
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 可以拦截新触发的调度.
Can a dispatch fired from inside reducer? so that the new fired dispatch can be intercepted by redux-saga.
推荐答案
无法从 reducer 触发调度
A dispatch cannot be fired from a reducer
如果检查状态必须由组件完成,则使用 connect
的第三个参数,又名 mergeProps:
If checking state must be done by the component, then use the 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 任务中检查状态:
If checking state does not need to be part of the component, then check the state in a saga task:
组件:
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)
}
这篇关于如何从 mapDispatchToProps 内部访问状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!