简体   繁体   中英

The correct way to re-render react component from another component

I have a component BoardManager with its initial state

const BoardManager = () => {
  const [boards] = useState([
    {
      name: "Board 1",
      link: "dkhgsdfj",
    },
    {
      name: "Board 2",
      link: "dkhgsdfj",
    },
  ]);

  return (
    <div>
      {boards.map((val, i) => (
        <Board boardName={val.name} />
      ))}
      <AddBoardButton boards={boards} />
    </div>
  );
};

And I have component AddBoardButton

function AddBoardButton({ boards }) {
  return (
    <div className="AddBoardButton">
      <button
        type="button"
        onClick={() => {
          boards.push({ name: "added board", link: "to be done" });
        }}
      >
        Add board
      </button>
    </div>
  );
}

The behaviour I want: I push the button and it adds new board

Questions:

  1. boards.push indeed change the state of BoardManager, but how should I make React to re-render the changes in BoardManager's state in correct way?
  2. And also, is changing the state of component A from component B is ok practice or should I avoid that?

boards.push indeed change the state of BoardManager, but how should I make React to re-render the changes in BoardManager's state in correct way?

You are mutating the state directly which is why your component isn't re-rendering. You need to update the state correctly to trigger a re-render on state update.

To update the state correctly, you need to create a new array and merge the old state with the new one. You also need to pass state setter function, returned by useState() hook, as a prop to the AddBoardButton component.

Board component:

// destructure state setter function
const [boards, setBoards] = useState([...]);

// pass the state setter function as a prop
<AddBoardButton boards={boards} setBoards={setBoards} />

AddBoardButton component:

const handleClick = () => {
  const newObject = { name: "added board", link: "to be done" };
  const updatedState = [...boards newObject];

  setBoards(updatedState); 
}

// set the onClick event handler on the button
<button type="button" onClick={handleClick} />

And also, is changing the state of component A from component B is ok practice or should I avoid that?

Child components can update the state that exists in the parent component.

There are two ways you can handle this:

  • pass the state setter function as a prop to the child component
  • create a callback function in the parent component and pass that callback function as a prop to the child component. This callback function should be responsible for updating the state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM