繁体   English   中英

useEffect 依赖项没有更新 useEffect

[英]useEffect dependency is not updating the useEffect

我有一个 useEffect 挂钩,在更改依赖项后没有更新。 依赖是通过 props 传递的状态变量。 下面是代码的样子:

const MyComponent = ({resource}) => {

// runs after changing resource state
console.log(resource)

useEffect(() => {
    setLoading(true);
      // doesnt run after changing resource state
      console.log(resource)
      setVariable(setDefaultValue());
    
  }, [resource]);

}

正在为“option1”或“option2”两种状态之一呈现 MyComponent,组件根据状态呈现不同的状态。 我这样称呼组件:

const [resource, setResource] = useState('option1');
const handleChange = (e) => {
    setResource(e.target.value);
};

return (
    <MyComponent resource={resource} />
)

我不明白为什么在资源状态更改后 useEffect 没有运行。 useEffect 外部的console.log显示更改状态,但useffect 内部的console.log在更改状态后不运行。

哦,你可以改一下上面的代码试试:

 //Parent Component const [resource, setResource] = useState('option1'); const [variable,setVariable] = useState(); const [loading,setLoading] = useState(false); useEffech(()=>{ let fetch_api = true; setLoading(true); fetch(URL,options).then(res=>res.json()) .then(res=>{ if(fetch_api){ setVariable(setDefaultValue()); setLoading(false); } }); return ()=>{ //remove memory fetch_api = false; } },[resource]); const handleChange = (e) => { setResource(e.target.value); }; return ( <MyComponent variable={variable} /> ) //Child Component const MyComponent=({variable})=>{ return <> </> }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM