【问题标题】:Get props in action -> reducer -> costum function获取 props in action -> reducer -> costum 函数
【发布时间】:2017-10-25 16:22:39
【问题描述】:

我有一个组件,它是另一个组件的“基础”。我想为新创建的组件添加更多功能

<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
}

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

【问题讨论】:

  • 你想将origin prop从SomeComponent传递给value_select,对吧?
  • @GrzegorzMotyl 没错!

标签: javascript reactjs redux jsx


【解决方案1】:

您需要在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 }
      />
   )
}

将新参数添加到您的句柄选择

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

然后action.payload.origin 内部的value_select 可以访问原点

当然现在你必须打电话给BetterComponent而不是SomeComponent

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

【讨论】:

  • 会不会是class BetterComponent extends someComponent{ 而不是React.Component?然后在这里render() { return ( &lt;SomeComponent 而不是这个render() { return ( &lt;BetterComponent
  • JS 中的继承很棘手,我认为最好像我一样使用包装器而不是继承(Composition over Inheritance - clean code rule ;))
  • BetterComponent 在渲染时返回 SomeComponent,只是改变了 onSelect 属性
  • 好的。我是否必须在render() { return ( &lt;SomeComponent ...this.props onSelect = { this.handleSelect } /&gt; ) } 我的整个组件`someComponent` 中重复?所有方法?
  • 不,这些将由SomeComponent 自己处理
猜你喜欢
  • 2019-08-01
  • 1970-01-01
  • 2015-02-15
  • 2017-12-05
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
相关资源
最近更新 更多