【问题标题】:Run useEffect only after prop is updated仅在更新道具后运行 useEffect
【发布时间】:2022-01-05 17:39:12
【问题描述】:
我将运行 API 调用所需的道具传递到我的组件中,我不希望它在初始渲染时运行,但仅在表单提交更新此道具后运行。即使我将道具放在依赖参数中,它仍然会在挂载时运行调用。如何防止 useEffect 在初始渲染时自动运行?也许我应该考虑一种完全不同的方法?
function GetData(props) {
const [propsState, propsSetState] = useState('');
useEffect(() => {
// Run API Call
}, [props])
}
【问题讨论】:
标签:
javascript
reactjs
use-effect
react-props
use-state
【解决方案1】:
const [mounted, setMounted] = useState(false);
useEffect(() => {
if (!mounted) {
setMounted(true);
return;
}
// Run API Call
}, [props])
【解决方案2】:
const ref = useRef();
useEffect(() => {
if (!ref.current) {
ref.current = true
return;
}
// Run API Call
}, [props])
【解决方案3】:
在您的返回语句中,使用逻辑 && 来评估在您的组件中运行 API 之前是否有更新。
{propState && <*YourComponent* />}
首先获取数据,一旦数据被检索,然后更新你的 const[] 中的状态,一旦它有值,你的组件然后渲染输出。