简体   繁体   中英

React props not getting updated when used in function

I have a really strange behaviour. I have the following code (super simple version):

const CanvasManager = () => {
  const [overlays, setOverlays] = useState([]);

  return <CanvasOverlay overlays={overlays} setOverlays={setOverlays} />
}



const CanvasOverlay = ({ overlays, setOverlays }) => {

  const [open,setOpen] = useState(false);

  // .. some code

  console.log(overlays) // First render: [], second render: [{id: 123}]

  const openEditOverlayDialog = id => {
    console.log(overlays) // First render: [], second render: []  <----- THIS IS THE PROBLEM
    const overlayData = overlays.find(o => o._id === id);
    setOpen(overlayData ); // <--- THIS IS WORKING, SO CONTEXT SEAMS RIGHT
  };

  const editOverlays = () => {
    const newOverlays = [...overlays];
    newOverlays.push({id: 123});
    setOverlays(newOverlays);
  }

  return <Button title="Edit Overlay 123" onClick={() => openEditOverlayDialog(123)} />
}

The first component has a state with overlays for a HTML5 canvas. It returns a component which handles the actual overlay. I can add a overlay {id: 123} there and it is set as a new overlay. It then is given as a prop to the CanvasOverlay component. When I console.log this it shows in the first console log but not in the on within the "openEditOverlayDialog" function.

What am I missing?

Help is much appreciate. Thank you all!

 const editOverlays = () => 
     setOverlays([...overlays, id: 123]);

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