reactjs - React TypeScript 16.8 如何向 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();
}, []);
推荐阅读
- ruby - 如何根据长度将路径数组转换为嵌套数组或散列
- python - 如何显示来自不同模型的对象?
- java - 能够获取 Box 文件夹项目,但无法使用 API 从 Box 下载文件
- css - JavaFX CornerRadiiConverter - 它在哪里?
- flutter - 容器中的子图像不遵循容器边框
- vue.js - 如何创建一个端点到 axios POST
- algorithm - 使用一次对 n 个元素进行排序的函数对 2n 个元素的数组进行排序
- javascript - 递归方式中层次树的构造逻辑
- spring - 数据未使用 H2 DB 从 Spring Boot 返回
- c++ - “const char *”类型的参数与“char *”类型的参数不兼容