繁体   English   中英

事件处理程序中的反应道具嵌套值不正确

[英]React prop nested value is incorrect in event handler

我有一个组件,它通过一个 object 作为其子代的道具,以及一个 function 来更新这个 object。 现在,我注意到其中一个孩子在读取 prop (obj.nested.property) object 的嵌套属性时总是返回安装时的初始值,尽管 prop (obj) 已成功更新 - 我可以在反应开发工具中看到这个,也从 useEffect console.log

这是结构:

const Parent = () => {
  const obj = useSelector(config);
  const setObj = (newObj) => {
    // update obj code
  }

  return (
    <Child obj={obj} onUpdate={setObj}/>
  )
}

const Child = ({ obj, onUpdate }) => {
  useEffect(() => {
    console.log(obj.nested.property);
    // here everything is correct. Every time the obj is updated, this logs the new 
    // obj.nested.property value
  }, [obj])

  const onBlur = (newValue) => {
    if (newValue !== obj.nested.property) {
      // here, after you change the value once, and then just click inside the input
      // and blur, this condition is always true, because obj.nested.property keeps the
      // value as it was on mount
      onUpdate(newValue)
    }
  }

  return (
    <Input value={obj.nested.property} onBlur={onBlur}/>
  )
}

您是否尝试使用该 object 进行 useState?

const Child = ({ propObj as obj, onUpdate }) => {
  
  const [obj,setObj]= useState(propObj);

  useEffect(() => {
    console.log(obj.nested.property);
    // here everything is correct. Every time the obj is updated, this logs the new 
    // obj.nested.property value
  }, [obj])

  const onBlur = (newValue) => {
    if (newValue !== obj.nested.property) {
      // here, after you change the value once, and then just click inside the input
      // and blur, this condition is always true, because obj.nested.property keeps the
      // value as it was on mount
      onUpdate(newValue)
    }
  }

  return (
    <Input value={obj.nested.property} onBlur={onBlur}/>
  )
}

根据反应文档,反应不会在调用 setState 函数后立即更新 state(因为 setState 是异步的)。 重新渲染组件后,新值将在 state 中设置(这里是子重新渲染)。 反应文档说:

setState() 不会立即改变 state 而是创建一个挂起的 state 转换。 在调用此方法后访问 state 可能会返回现有值。 无法保证对 setState 的调用同步操作,并且可能会批处理调用以提高性能。

因此,在调用组件 setState function 并更新状态后(在重新渲染组件之前),state 的值是之前的值。 但在组件重新渲染后调用的 useEffect 中,state 具有新的价值。 你可以看到这个以获取更多信息。

暂无
暂无

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

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