search

Home  >  Q&A  >  body text

Functional Components React - updating a state causes the entire page to re-render

<p>Thank you very much for your help in advance. I'm not sure why when I update the <code>percentageDone</code> state in <code>loadDataFunction()</code> it updates <code>RenderData1Component</code> when in fact it It shouldn't be like this. Shouldn't it only update when data1 changes? </p> <p>I have a piece of code like this. </p> <pre class="brush:php;toolbar:false;">const [loading, setLoading] = useState(true); const [data1, setData1] = useState(null); const [percentageDone, setPercentageDone] = useState(0); LoadDataFunction(){ // Call multiple apis (let's say there are 10) in one promise and call setPercentageDone() when each api completes. } useEffect( () => { LoadDataFunction() },[]) useEffect( () => { if (condition satisfied) { LoadDataFunction() // Reload the latest data } }, [condition]) return ( loading ? percentageDone : <RenderData1Component data={data1}> )</pre> <p>I only want to update <code><RenderData1Component data={data1}></code> when the <code>data1</code> state is updated, not <code>percentageDone< /code>. But whenever I update <code>setPercentageDone()</code>, it also triggers a re-rendering of <code><RenderData1Component data={data1}></code>. </p>
P粉180844619P粉180844619454 days ago387

reply all(1)I'll reply

  • P粉904405941

    P粉9044059412023-08-18 11:26:59

    I'm not sure, but this might help you.

    const [loading, setLoading] = useState(true);
    const [data1, setData1] = useState(null);
    const [percentageDone, setPercentageDone] = useState(0);
    
    const loadDataFunction = async () => {
      // 执行 API 调用并更新 percentageDone
    };
    
    useEffect(() => {
      loadDataFunction().then(() => {
        setLoading(false);
      });
    }, []);
    
    useEffect(() => {
      if (condition) {
        setLoading(true);
        loadDataFunction().then(() => {
          setLoading(false);
        });
      }
    }, [condition]);
    
    return (
      loading ? (
        <div>{percentageDone}% 加载中...</div>
      ) : (
        <RenderData1Component data={data1} />
      )
    );

    Possibly you are giving multiple conditions, which may cause problems. Please check this out too.

    reply
    0
  • Cancelreply