在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,
})
}
答案 0 :(得分:1)
如何将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();
}, []);