【问题标题】:React how to use state in passed function反应如何在传递的函数中使用状态
【发布时间】:2019-10-27 10:37:59
【问题描述】:

我正在使用 React 上下文来传递状态。当我的状态发生变化时,子组件也会发生变化(控制台日志显示新值),但是当在函数中使用此状态时,它不会在那里更新(console.log 显示旧值)。

我需要重新渲染函数吗?怎么样?

  const {user, userInfo, ref} = useSession(); <-- wrapper for useContext
  console.log(userInfo); <--- correct, updated value

  const haalDataOp = async () => {
    console.log(userInfo.enelogic); <--- old value displaying
    ...
  }

我正在使用按钮 (onClick) 中的函数 haalDataOp

正如有人已经提到的,我可以使用 useRef,但我不明白为什么。为什么这个简单的例子有效(摘自https://dev.to/anpos231/react-hooks-the-closure-hell-71m),而我的代码却无效:

  const [value, setValue] = useState(1);

  const handleClick = useCallback(
    () => {
      setValue(value + 1)
    },
    [value],
  );

我还尝试在我的示例中使用 useCallback(在 dep 数组中使用 userInfo),但这并没有奏效。

【问题讨论】:

  • 您在哪里/如何使用haalDataOp
  • 从一个按钮,添加到文章中

标签: reactjs


【解决方案1】:

const ... userInfo ... 是一个常量,所以在一个 Component 中如下所示:

console.log('render', userInfo.enelogic) // different value in each render
const haalDataOp = async () => {
  console.log('before', userInfo.enelogic) // correct old value
  await update()
  console.log('after', userInfo.enelogic)  // still the same old value
}

return <button onClick={haalDataOp} />

...它会记录:

render old
before old
after old
render new

...因为haalDataOp 中的userInfo 是一个引用原始渲染值的闭包。如果您需要访问一个指向未来渲染的最新值的可变引用,您可以useRef

const userInfoRef = useRef()
userInfoRef.current = userInfo

console.log('render', userInfo.enelogic) // different value in each render
const haalDataOp = async () => {
  console.log('before', userInfoRef.current.enelogic) // old value
  await update()
  console.log('after', userInfoRef.current.enelogic)  // should be new value
}

return <button onClick={haalDataOp} />

但是,可能存在竞争条件和/或'after' 代码的执行确定性地发生在下一次渲染之前,在这种情况下,您将需要使用其他技巧...

我怀疑这种情况需要const {ref} = useSession(),所以请阅读文档。

【讨论】:

  • 嗨,我正在尝试阅读您的答案,但对我来说不是很清楚。我没有在这个 haalDataOp 函数中更新我的状态,我只是在用那个状态做一些事情。状态由其他进程更新(在这种情况下 Firebase 更新我的状态),我希望在我的子组件中使用新状态。 (useSession 钩子中提到的 ref 是 firestore ref,而不是 react ref)
  • 它确实使用 useRef 工作,但我仍然不明白它是如何工作的。我的另一个问题stackoverflow.com/questions/58569798/… 也是这个问题吗?
猜你喜欢
  • 2023-01-16
  • 2021-01-04
  • 2017-03-24
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
相关资源
最近更新 更多