简体   繁体   中英

React hook state updated in parent but child component does not receive new props

I'm using a css grid layout with a differing amount of columns and rows based on screen size.

import React, { useState, useEffect } from 'react'

function Main() {

  const [numRows, setNumRows] = useState(10)
  const [numColumns, setNumColumns] = useState(10)

  const layoutList = [
      <Content {...props} />,
      <Content {...props2} />,
      <Profile {...props3} numColumns={numColumns} />,
    ]

  const [layout, setLayout] = useState(layoutList)

  let gridCount = () => {
    //code to count number of columns and rows
    //uses setNumRows and setNumColumns passed down as props
  }

}

After creating a layout of my components I define a function to count the num of rows and columns.

useEffect(() => {
  gridCount()
  window.addEventListener("resize", gridCount)
})

I add a resize eventlistener which works, I can see that state is being updated in the parent component Main. However when I check the state of the child component Profile I see that it was initialized with 10 but never gets accessed again, no new props are being sent to even though the Main state is being updated correctly. I'm trying to get a rerender in the child but I'm unsure why the parent is not sending updated props, any state change in the parent should cause a rerender correct?

Hard to tell exactly from the code available, but I suspect the children do not receive the new props because those children are stored in state and never updated.

To fix this you should update the children whenever you update numRows or numColumns . Since there isn't usually a good reason to store children in a state variable (and it can lead to issues like this where you have to manually tell the children to update instead of letting React handle that), I would recommend removing the state storage for layout entirely and just rendering the children like usual. Just use layoutList directly in your returned element.

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