Functional Components React - updating a state causes the entire page to re-render
P粉180844619
P粉180844619 2023-08-17 14:19:48
0
1
421
<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粉180844619
P粉180844619

reply all(1)
P粉904405941

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template