简体   繁体   English

useEffect 依赖项没有更新 useEffect

[英]useEffect dependency is not updating the useEffect

I have a useEffect hook that is not updating after changing the dependency.我有一个 useEffect 挂钩,在更改依赖项后没有更新。 The dependency is a state variable passed through props.依赖是通过 props 传递的状态变量。 Included below is what the code looks like:下面是代码的样子:

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]);

}

MyComponent is being rendered for one of two states 'option1' or 'option2' the component renders differently depending on the state.正在为“option1”或“option2”两种状态之一呈现 MyComponent,组件根据状态呈现不同的状态。 I call the component like so:我这样称呼组件:

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

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

I don't understand why the useEffect isn't running after resource state is changed.我不明白为什么在资源状态更改后 useEffect 没有运行。 The console.log on the outside of the useEffect show the change state, but the console.log inside of the useffect isn't run after changing state. useEffect 外部的console.log显示更改状态,但useffect 内部的console.log在更改状态后不运行。

Oh, you can change code the following above try:哦,你可以改一下上面的代码试试:

 //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