获取 props in action -> reducer -> costum function

Get props in action -> reducer -> costum function

我有一个组件是另一个组件的 "base"。我想为新创建的组件添加更多功能

<SomeComponent
onSelect = { this.props.handleSelect }
onDeselect = { this.props.handleDeselect }
selectionList = { valuesList }
value = { values }
origin = "XYZ" />

onSelect 触发动作 this.props.handleSelect

export function handleSelect(value) {
    return dispatch => {
        dispatch(actionCreator(HANDLE_SELECT, value));
    }
}

该操作进入 reducer

case HANDLE_SELECT: {
    const newValues = value_select(state, action);
        return {
            ...state,
            find: {
                ...state.a, 
                values: newValues
            }
        }
 }

最后,value_select 被调用来完成所有魔术

export const value_select = function(state, action) {
    ...

    const newData = {
    XYZ: action.payload
    }
    return newData
}

我如何在 value_select() 中从我的 component 中获取 props 中的 "a"。我在 XYZ 所在的地方需要它... 请注意,我无法将任何内容写入 onSelect,因此 onClick 事件。我正在使用我不想更改的预先设计的 component。只有components是基于原来的

您需要在 SomeComponent 中添加另一个处理程序,并添加新参数和您要传递给原始 handleSelect 的属性。如果 SomeComponent 来自供应商并且您无法更改它的代码,那么您将不得不包装它

class BetterComponent extends React.Component{
handleSelect = (value) {
    this.props.handleSelect(value, this.props.origin)
}

render() {
   return (
      <SomeComponent
        ...this.props
        onSelect = { this.handleSelect }
      />
   )
}

为您的句柄添加新参数select

export function handleSelect(value, origin) {
    return dispatch => {
        dispatch(actionCreator(HANDLE_SELECT, {
           value: value,
           origin: origin
        }));
    }
}

然后 action.payload.originvalue_select

中可以访问 origin

当然现在你必须调用 BetterComponent 而不是 SomeComponent

<BetterComponent
onSelect = { this.props.handleSelect }
onDeselect = { this.props.handleDeselect }
selectionList = { valuesList }
value = { values }
origin = "XYZ" />