React hooks 随时更新 [英] React hooks update sort of whenever they feel like it

查看:38
本文介绍了React hooks 随时更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我使用钩子来管理一组表单的状态,设置如下:

So, I'm using hooks to manage the state of a set of forms, set up like so:

    const [fieldValues, setFieldValues] = useState({}) // Nothing, at first

设置值时,状态不会更新:

When setting the value, the state doesn't update:

    const handleSetValues = values => {
        const _fieldValues = {
            ...fieldValues,
            ...values
        }

        setFieldValues(_fieldValues)

        console.log(fieldValues) // these won't be updated

        setTimeout(() => {
            console.log(fieldValues) // after ten seconds, it's still not updated
        },10000)
    }

如果我第二次调用该函数,它会更新,但这对我不起作用.我从未在类组件中看到过这样的行为.

If I call the function a second time, it'll have updated, but that's not gonna work for me. I never saw behaviour like this in class components.

它的意思是...喜欢,而不是更新吗?还是只要感觉合适就更新?真是令人困惑的行为.

Is it meant to... like, not update? Or just update whenever it feels like it? Really confusing behaviour.

推荐答案

setFieldValues(_fieldValues) 是一个异步调用,意味着您将无法在下一行获得结果.

setFieldValues(_fieldValues) is an async call, means you won't able to get the result in the very next line of this.

您可以使用 useEffect 钩子.

useEffect(() => {
    // do your work here
  }, [fieldValues]);

从你的问题看你有React的Class组件背景,所以useEffect类似于componentDidMountcomponentDidUpdate生命周期方法.

It seems from your question that you have background of Class components of React, so useEffect is similar to componentDidMount and componentDidUpdate lifecycle methods.

useEffect 每当依赖数组中的状态(在您的情况下为 [fieldValues])发生变化时调用,并且您在 useEffect 主体中获得更新的值.

useEffect calls whenever the state in the dependency array (in your case [fieldValues]) changes and you get the updated value in useEffect body.

您也可以在 useEffect 中执行 componentWillUnmount 工作.

You can also perform componentWillUnmount work in useEffect as well.

有一个简短的指南.

这篇关于React hooks 随时更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆