React/Redux - 添加元素而不是替换状态

React/Redux - Add element instead of replacing state

我正在使用 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));
  };

您在减速器中使用 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那,除非你想将你的状态重置为它。