如何使用Redux动态添加输入?

时间:2019-04-23 21:18:14

标签: javascript reactjs ecmascript-6 redux react-redux

在使用本地状态执行此操作之前,现在需要将其传递给Redux。我没有使用Redux表单,也不会使用。

这是我/我使用useState钩子在本地状态下进行的操作:

const DynamicInputExample = () => {

    const [addShareStructureInput, setAddShareStructureInput] = useState({
      inputs: ['input-0'],
    });

    const appendInput = () => {
      const newInput = `input-${addShareStructureInput.inputs.length}`;
      setAddShareStructureInput(prevState => ({ inputs: prevState.inputs.concat([newInput]) }));
    };


  return(
    <div id="dynamicInput">
      // HERE I MAP THE INPUTS
      {addShareStructureInput.inputs.map(input => (
        <FormField
          key={input}
          onChange={() => onChange()}
        />
      ))}
      <div>
        <Button
          type="button"
          // HERE I CALL THE FUNCTION TO ADD NEW INPUT
          onClick={() => appendInput()}
        >
          + Add More
        </Button>
      </div>
    </div>
  )
}

但是现在我需要删除该代码上的钩子,并在Redux上进行相同的逻辑。

这是我到目前为止所做的: 动作:

export const shareStructureInputsAction = shareStructureInputs => ({
  type: ActionTypes.SHARE_STRUCTURE_INPUTS,
  payload: { shareStructureInputs },
});

减速器:

const initialState = {
  shareStructureInputs: ['input-0'],
}

const handlers = {
  [ActionTypes.SHARE_STRUCTURE_INPUTS](state, action) {
    return {
      ...state,
      // BELOW I NEED TO ADD THE LOGIC TO KEEP THE STATE OF THE INPUTS ADDED
      shareStructureInputs: {
        ...action.payload.shareStructureInputs,
      },
    };
  },
}

那么,我该如何使用Redux模拟相同的逻辑/行为?

2 个答案:

答案 0 :(得分:1)

可以使用以下方法做到这一点:

const initialState = {
  shareStructureInputs: ['input-0'],
}

const handlers = {
  [ActionTypes.SHARE_STRUCTURE_INPUTS](state, action) {
    return {
      ...state,
      shareStructureInputs: [...shareStructureInputs, action.payload.shareStructureInputs],
    };
  },
}

答案 1 :(得分:1)

操作:

np.nanstd(df[cols], ddof=1)

减速器:

export const shareStructureInputsAction = shareStructureInputs => ({
  type: ActionTypes.SHARE_STRUCTURE_INPUTS,
  payload: shareStructureInputs
});

const initialState = {
  shareStructureInputs: ['input-0'],
}

const handlers = {
  [ActionTypes.SHARE_STRUCTURE_INPUTS](state, action) {
    return {
      ...state,
      shareStructureInputs: action.payload
    };
  },
}