[英]React TypeScript 16.8 How to add a dependency to useEffect()
在 useEffect() 中,我创建了一些键,然后尝试调用不在 useEffect() 块中的函数 addKeysToState() 并且它导致错误。
我尝试在 useEffect() 结束时将 'addKeysToState' 和 addKeysToState() 添加到数组中,但无济于事。
我得到的错误是...
React Hook useEffect has a missing dependency: 'addKeysToState'. Either include it or remove the dependency array react-hooks/exhaustive-deps
代码片段...
const FeedbackForm: React.FC<props> = ({publicKey}) => {
const [formState, setState] = useState();
useEffect(() => {
const genRandomKey = async () => {
const tempPrivateKey = await ecc.randomKey();
if (tempPrivateKey) {
const tempPublicKey = await ecc.privateToPublic(tempPrivateKey);
if (tempPublicKey) {
addKeysToState(tempPrivateKey, tempPublicKey);
}
}
};
genRandomKey();
}, []);
const addKeysToState = (tempPrivateKey: string, tempPublicKey: string) => {
setState({
...formState,
tempPrivateKey,
tempPublicKey,
})
}
把addKeysToState
放在钩子里怎么样? 看起来它不是依赖项,而是实现细节。
请注意,由于addKeysToState
使用先前的状态,因此我们应该改用回调形式,以避免竞争条件。
const FeedbackForm: React.FC<props> = ({publicKey}) => {
const [formState, setState] = useState();
useEffect(() => {
const addKeysToState = (tempPrivateKey: string, tempPublicKey: string) => setState((prevState) => ({
...prevState,
tempPrivateKey,
tempPublicKey,
))
const genRandomKey = async () => {
const tempPrivateKey = await ecc.randomKey();
if (tempPrivateKey) {
const tempPublicKey = await ecc.privateToPublic(tempPrivateKey);
if (tempPublicKey) {
addKeysToState(tempPrivateKey, tempPublicKey);
}
}
};
genRandomKey();
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.