Reactjs React TypeScript 16.8如何向useEffect()添加依赖项
在useffect()中,我生成了一些键,然后尝试调用不在useffect()块中的函数addKeyState(),它导致了一个错误 我尝试在useffect()的末尾将'addKeyState'和addKeyState()添加到数组中,但没有成功 我得到的错误是Reactjs React TypeScript 16.8如何向useEffect()添加依赖项,reactjs,Reactjs,在useffect()中,我生成了一些键,然后尝试调用不在useffect()块中的函数addKeyState(),它导致了一个错误 我尝试在useffect()的末尾将'addKeyState'和addKeyState()添加到数组中,但没有成功 我得到的错误是 React Hook useffect缺少依赖项:“addKeyState”。包括它或删除依赖项数组react hooks/deps 代码片段 const FeedbackForm: React.FC<props> = (
React Hook useffect缺少依赖项:“addKeyState”。包括它或删除依赖项数组react hooks/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,
})
}
const FeedbackForm:React.FC=({publicKey})=>{
const[formState,setState]=useState();
useffect(()=>{
const genRandomKey=async()=>{
const tempPrivateKey=等待ecc.randomKey();
if(临时私钥){
const tempPublicKey=等待ecc.privateToPublic(tempPrivateKey);
if(临时公钥){
AddKeyState(tempPrivateKey、tempPublicKey);
}
}
};
genRandomKey();
}, []);
const addkeystate=(tempPrivateKey:string,tempPublicKey:string)=>{
设置状态({
…formState,
临时私人钥匙,
临时公钥,
})
}
把addkeystate
放在钩子里怎么样?看起来这不是一个依赖项,而是一个实现细节
请注意,由于addkeystate
使用前一个状态,因此我们应该使用回调表单,以避免出现赛车情况
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();
}, []);
const FeedbackForm:React.FC=({publicKey})=>{
const[formState,setState]=useState();
useffect(()=>{
const addkeystate=(tempPrivateKey:string,tempPublicKey:string)=>setState((prevState)=>({
…国家,
临时私人钥匙,
临时公钥,
))
const genRandomKey=async()=>{
const tempPrivateKey=等待ecc.randomKey();
if(临时私钥){
const tempPublicKey=等待ecc.privateToPublic(tempPrivateKey);
if(临时公钥){
AddKeyState(tempPrivateKey、tempPublicKey);
}
}
};
genRandomKey();
}, []);
react-then投诉react-Hook-useffect缺少依赖项:“formState”。包括它或删除依赖项数组。如果在“setState”调用中只需要“formState”,您还可以执行函数更新“setState(f=>…)”
是否可以确保使用回调表单?(我在提交后几秒钟编辑了答案:p)