我有一个名为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
中读取的输入值是更新的值?
答案 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
。