[英]Can you make useEffect run only once when one of the dependencies changes but not if it changes again?
I am rendering conditional content and I have我正在渲染有条件的内容,我有
const [content,setContent] = useState(0);
const [data,setData] = useState([]);
let render;
switch(content)
{
case 0:render=<Something/>; break;
case 1:render=<Else/> ;break;
}
I have some data which will be used only if we render <Else/>
but the user can switch between <Something>
and <Else/>
with a radio button anytime.我有一些数据,只有在我们渲染
<Else/>
时才会使用,但用户可以随时使用单选按钮在<Something>
和<Else/>
之间切换。 I don't want to load the data if users never switches to <Else/>
, but I also don't want to load data again in case he switches from <Else/>
to <Something/>
and then again to <Else/>
如果用户从不切换到
<Else/>
我不想加载数据,但我也不想再次加载数据以防他从<Else/>
切换到<Something/>
然后再切换到<Else/>
so using useEffect(()=>{loadData().then(response=>setData(response.data))},[content])
not good idea since it will run everytime the user switches, but if I use useEffect(()=>{loadData().then(response=>setData(response.data))},[])
and user never switched to I loaded unnecessary data?所以使用
useEffect(()=>{loadData().then(response=>setData(response.data))},[content])
不是一个好主意,因为它会在每次用户切换时运行,但是如果我使用useEffect(()=>{loadData().then(response=>setData(response.data))},[])
并且用户从未切换到我加载了不必要的数据? How can I avoid this problem?我怎样才能避免这个问题?
What you can do it's validate inside the useEffect
hook if the data you need was already loaded.如果您需要的数据已经加载,您可以在
useEffect
钩子中进行验证。 If that's the case, then just avoid making the request.如果是这种情况,那么就避免提出请求。
Or或者
Pass the responsability of fetch the data to the child components ( Else
and Something
).将获取数据的责任传递给子组件(
Else
和Something
)。 That way it will only be executed when that component it's rendered.这样,它只会在该组件被渲染时执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.