react-beautiful-dnd 组件道具更改不会触发重新渲染

时间:2021-04-08 11:56:13

标签: reactjs react-beautiful-dnd

我正在使用react-beautiful-dnd构建一个简单的垂直拖放列表,并且列表是动态且可扩展的,但是当我更新传递给dnd组件的列表时,dnd组件并没有重新渲染。

我只是假设当按钮被点击时,状态会更新,DND 组件应该随着道具的改变而重新渲染。问题是状态已更新,但 dnd 组件未更新。

下面是代码。预先感谢您的帮助。

应用文件

import { Box, Button } from "@material-ui/core";
import React, { useState } from "react";
import DND from "../components/DND";

interface AppProps {}

const App: React.FC<AppProps> = ({}) => {

  const [state, setstate] = useState([0]);
  const handleClick = () => {
    const newState = [...state];
    newState.push(state[state.length - 1] + 1);
    setstate(newState);
  };

  return (
    <Box px={2}>
      <Box>{JSON.stringify(state)}</Box>
      <DND initialIds={state} />
      <Button onClick={handleClick}>++</Button>
    </Box>
  );
};

export default App;

拖放组件

import { Box } from "@material-ui/core";
import React, { useState } from "react";
import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";

const reorder = (list: number[], startIndex: number, endIndex: number) => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);
  return result;
};

const DND: React.FC<{}> = ({ initialIds }) => {
  const [ids, setIds] = useState(initialIds);

  const onDragEnd = (result: any) => {
    if (!result.destination) {
      return;
    }
    const newList = reorder(ids, result.source.index, result.destination.index);
    setIds(newList);
  };

  return (
    <Box>
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable droppableId="droppable">
          {(provided, snapshot) => (
            <div
              {...provided.droppableProps}
              ref={provided.innerRef}
              style={getListStyle(snapshot.isDraggingOver)}
            >
              {ids.map((id, index) => (
                <Draggable key={id} draggableId={id.toString()} index={index}>
                  {(provided, snapshot) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                      style={getItemStyle(
                        snapshot.isDragging,
                        provided.draggableProps.style
                      )}
                    >
                      {id}
                    </div>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </Box>
  );
};

export default DND;

enter image description here

0 个答案:

没有答案