简体   繁体   English

React useEffect,仅在状态更改后调用

[英]React useEffect, only call after a state change

We are using react recollect as state management tool.我们使用 react recollect 作为状态管理工具。 In this useEffect below, I want to call appStore.getSettingsHistory() function only if the states in array dependency does change.在下面的这个 useEffect 中,只有当数组依赖中的状态发生变化时,我才想调用 appStore.getSettingsHistory() 函数。 But based on the below code, when component mounts, we see 5 calls (as many as in array) initially, then other calls as those state change.但是根据下面的代码,当组件挂载时,我们最初会看到 5 个调用(与数组中的一样多),然后随着这些状态的变化而进行其他调用。 How can I achieve, calling this api (appStore.getSettingsHistory()) only once in the beginning, then as these states change.我怎样才能实现,在开始时只调用这个 api (appStore.getSettingsHistory()) 一次,然后随着这些状态的变化。

useEffect(() => {
  appStore.getSettingsHistory();
}, [store.brandPrefs, store.formularies, store.selectedFormularyName, store.settings.showMaskToPatient, store.settings.sendMessageOnComplete])

I suppose you could create another state variable and check whether your component is first rendered and in that case call the API once and in other cases call it based on the dependency array.我想您可以创建另一个状态变量并检查您的组件是否首先呈现,在这种情况下调用 API 一次,在其他情况下根据依赖数组调用它。 Something like this -像这样的东西-

const [mounted, setMount] = useState(false);
if(!mounted){
    useEffect(() => {
    appStore.getSettingsHistory();
    setMount(true);
    },[])
}
else{
    useEffect(() => {
    appStore.getSettingsHistory();
    }, [store.brandPrefs, store.formularies, store.selectedFormularyName, 
    store.settings.showMaskToPatient,  store.settings.sendMessageOnComplete])
}
     

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

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