反应useState值未在ref回调中更新

时间:2020-01-16 12:16:40

标签: javascript reactjs ref react-functional-component use-state

我有一个名为SignUp的功能组件,它使用Google Recaptcha来保护注册表单。

Signup创建一个指向Recaptcha组件的引用,并声明一个指向函数方法onResolved的回调函数onRecaptchaResolved

问题在于,在执行Recaptcha之后调用onRecaptchaResolved时,我们输入的值不是最新状态,而是useState设置的初始值 在我们的情况下"hi"

import React, { useState } from 'react';
import styled from 'styled-components';
import Recaptcha from 'react-google-invisible-recaptcha';

const Input = styled.input``

function SignUp({dispatch}) {
    const [inputValue, setInputValue] = useState("hi");
    let recaptcha = null; // this will be our ref

    const formSubmit = () => {
         recaptcha.execute()
    }

    const onRecaptchaResolved = ( recaptchaToken) => {
         console.log(inputValue); // always logs; "hi"
    }


    return (
        <>          
            <Input 
                placeholder="you@example.com"
                type="text"
                value={inputValue}
                onChange={e => setInputValue(e.target.value)
                }
            />
            <Recaptcha
                ref={ ref => recaptcha = ref }
                sitekey={ "{MY_SITE_KEY}" }
                onResolved={recaptchaToken =>{ onRecaptchaResolved(recaptchaToken)} } 
            />

            <SubmitButton onClick={formSubmit}> Submit email</SubmitButton>
        </>
    )
}

如何确保在onRecaptchaResolved中读取的输入值是更新的值?

1 个答案:

答案 0 :(得分:2)

react-google-invisible-recaptcha似乎存储onResolved中提供的初始值,除非重新安装<Recaptcha>,否则不会更新它。看到 https://github.com/szchenghuang/react-google-invisible-recaptcha/blob/master/src/index.js#L41

最简单的确认方法是在key上更改时,在<Recaptcha>上设置inputValue