【问题标题】: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[] 中的状态,一旦它有值,你的组件然后渲染输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 2021-04-07
        • 2020-03-02
        • 2020-01-16
        相关资源
        最近更新 更多