使用useContext在React中记录状态

时间:2019-10-27 23:44:18

标签: javascript reactjs

我正在尝试传递信息以设置状态,该状态是react中useContext / useState的一部分。但这不允许我更改对象。我该怎么做呢?谢谢

const PlayableSquare = ({ style, children, row, col }) => {
  const { board, setBoard } = useContext(BoardContext);

  const drop = e => {
    e.preventDefault();
    const data = e.dataTransfer.getData("transfer");
    e.target.appendChild(document.getElementById(data));
    const color = e.dataTransfer.getData("color");
    const prevRow = e.dataTransfer.getData("row");
    const prevCol = e.dataTransfer.getData("col");
    const counter = e.dataTransfer.getData("counter");
    board["board"]["board"][prevRow][prevCol] = 0; //THIS IS THE PROBLEM LINE
    board["board"]["locations"][color][counter] = [row, col];//THIS TOO
    setBoard(board);
  };

  const allowDrop = e => {
    e.preventDefault();
  };

  return (
    <div
      className="playable"
      onDrop={drop}
      onDragOver={allowDrop}
      style={style}
    >
      {children}
    </div>
  );
};

export default PlayableSquare;

我收到此错误:

Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node

但是,如果我用board [“ board”] ...注释掉行,就可以了

const Board = () => {
  const [board, setBoard] = useState(initialBoard);
  const [locations, setLocations] = useState(initialLocations);
  const providerValue = useMemo(
    () => ({ board, setBoard, locations, setLocations }),
    [board, setBoard, locations, setLocations]
  );
  return (
    <BoardContext.Provider value={providerValue}>
      <BoardGrid>{makeBoard()}</BoardGrid>
    </BoardContext.Provider>
  );
};

0 个答案:

没有答案