【问题标题】:React/Redux - Add element instead of replacing stateReact/Redux - 添加元素而不是替换状态
【发布时间】:2021-11-02 19:11:16
【问题描述】:

我正在使用https://reactflow.dev/ 库并且在 Redux 状态下,当我添加一个新元素而不是将其添加到数组时,它会用新元素替换前一个元素。

减速器

import * as types from '../actions/types';

const initialState = {
  elements: [],
  currentElement: undefined,
};

const flow = (state = initialState, action) => {
  switch (action.type) {
    case types.ADD_ELEMENT:
      return {
        ...initialState,
        elements: initialState.elements.concat(action.payload),
        // elements: [...initialState.elements, action.payload],
      };
  }
}

动作

import { ADD_ELEMENT } from './types';

export const addElement = (node) => (dispatch) => {
  dispatch({
    type: ADD_ELEMENT,
    payload: node,
  });
};

DndFLow

const onDrop = (event) => {
    event.preventDefault();

    const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect();
    const type = event.dataTransfer.getData('application/reactflow');
    const position = reactFlowInstance.project({
      x: event.clientX - reactFlowBounds.left,
      y: event.clientY - reactFlowBounds.top,
    });

    const newNode = {
      id: getId(),
      type,
      position,
      data: { label: `${type}` },
    };

    addElement(newNode);
    setElements((es) => es.concat(newNode));
  };

【问题讨论】:

    标签: javascript reactjs redux react-redux redux-thunk


    【解决方案1】:

    您在减速器中使用initialState,而不是状态。

    使用状态可能会解决您的问题:

    const flow = (state = initialState, action) => {
      switch (action.type) {
        case types.ADD_ELEMENT:
          return {
            ...state,
            elements: state.elements.concat(action.payload),
          };
      }
    }
    

    state = initialState 是正确的,因为这意味着如果 state 没有任何值,它将默认使用 initialState,但除此之外,您不应使用 initialState,除非您想重置您的告诉它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 2014-04-15
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 2015-11-07
      • 2022-01-27
      相关资源
      最近更新 更多