简体   繁体   English

儿童道具活动不持有家长当前 state

[英]Children props event doesn't hold parent's current state

I have a state variable which holds components created dynamically, however, when I access the state from a function passed to the child as props, I get the state status from back when it was created. I have a state variable which holds components created dynamically, however, when I access the state from a function passed to the child as props, I get the state status from back when it was created. Not so when I log useEffect.当我记录useEffect时不是这样。

For example: I add 3 children, and in the function logMyChildren I get the state previous to the creation of the last Child element.例如:我添加了 3 个子元素,在 function logMyChildren 中,我在创建最后一个子元素之前得到了 state。

First Child mychildren is []我的第一个mychildren是 []

Second Child myChildren is [{Child with id 0}]第二个孩子myChildren是 [{Child with id 0}]

Third Child myChildren is [{Child with id 0}, {Child with id 1}]第三个孩子myChildren是 [{Child with id 0}, {Child with id 1}]

It gives me the same state with each Child every time I call that function.每次我调用 function 时,它都会给我与每个孩子相同的 state。

Is there a way to get the current state(not a state from the past) regardless of the children?不管孩子们有没有办法获得当前状态(不是过去的 state)?

const Parent = () => {
  const [myChildren, setMyChildren] = useState([])

  const addChild = () => {
    let id = myChildren.length + 1
    setMyChildren([
      ...myChildren,
      <Child key={id} id={id} logMyChildren={logMyChildren} />,
    ])
  }

  const logMyChildren = (id) => {
    console.log(id, myChildren)
  }

  useEffect(() => {
    console.log(myChildren)
  }, [myChildren])

  return (
    <>
      <button onClick={addChild}>Add a child</button>
      {myChildren && myChildren.map((child) => child)}
    </>
  )
}

const Child = ({ id, logMyChildren }) => {
  return (
    <>
      <p>A child with id {id}!</p>
      <button onClick={() => logMyChildren(id)}>X</button>
    </>
  )
}

Every time useEffect() runs, it has the updated state.每次useEffect()运行时,它都会更新 state。 Thanks.谢谢。

The problem for you is that you are creating logMyChildren that encloses state variable (in your case mychildren ).您的问题是您正在创建包含logMyChildren变量的 logMyChildren (在您的情况下mychildren )。 What you could do is to use useRef你可以做的是使用useRef

Something like this:像这样的东西:

const stateRef = useRef();
stateRef.current = myChildren;

And then in logMyChildren you use ref - stateRef :然后在logMyChildren中使用 ref - stateRef

console.log(id,stateRef.current);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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