简体   繁体   中英

React component is updating late

I am using React.useEffect() and the results are updating late. Why is that so ?

function Process(props) {
  const [results, setResults] = React.useState({
    number: "",
    f: {}
  });

  let data = props.data; //returns object from another component which changes

  React.useEffect(() => {
    return () => setResults(data)
  }, [data]);

  return (
    <p>{results.number}</p> //ouputs previous number
  );
};

Please tell me if you need the component which passes the props={data} to Process() component.

Thanks

if props.data is already a useState there is no need for using another useEffect and useState, React already handles that and you can just use the value

function Process(props) {
   let data = props.data;

  return <p> { data.number } </p>
}

the return value of a useEffect function is a function that get's called to clean what the useEffect does

if you want to run the setResults as soon as data change, do that in the body of the function

React.useEffect(() => {
  setResults(data)
}, [data]);

https://reactjs.org/docs/hooks-effect.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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