SetXXXXX in useState is an asynchronous function. When useState is stored for the first time, it may fail to be stored

Because the update of state in react is asynchronous, after we setState, react will not immediately change the value, but temporarily put it into the pedding queue. React will merge multiple states and render only once, so don’t use useState in a loop. It may render only the value of the last set, but when a function is passed in, it will be put into a queue and executed in the order it was called

  • Juejin. Cn/post / 684490…
  • The original code

  • console.log

Method 1: Use ref

  • If you deliberately want to read the latest state from some asynchronous callback, you can use a ref to save it, modify it, and read from it
const App = () => {
  const [arr, setArr] = useState([0]);
  let ref = useRef();
  useEffect(() => {
    ref.current = arr;
    console.log(arr);
  });

  const handleClick = () => {
    Promise.resolve().then(() => {
      const now = [...ref.current, 1];
      ref.current = now;
      setArr(now);
    })
      .then(() => {
        setArr([...ref.current, 2]);
      });
  }

  return (
      <button onClick={handleClick}>change</button>
  );
}
Copy the code

Method 2: Pass parameters in callback mode

const handleClick = () => { Promise.resolve().then(() => { setArr(prevState => [...prevState, 1]); / / here also can not change, use setArr ([... arr, 1])}), then (() = > {setArr (prevState = > [... prevState, 2)); });}); }Copy the code

UseEffect ()

  • The problem with asynchronous data retrieval is that I use the useEffect to store the data twice. It is not possible to solve the problem. The rest is not important
const [categtry, setCategtry] = useState([]); const [categData, setCategData] = useState([]); useEffect(() => { getCollaCategory(); } []); UseEffect (() => {// useEffect applies again if (categtry) {setCategData(try); } }, [categtry]); const getCollaCategory = async () => { const { resp } = await call(service.getCollaCategory); If (resp. Code = = = 0) {/ / although assignment here for the first time, but the outside want to get categtry the variable is empty setCategtry (resp. CategoryTree. SubCategoryList); }}Copy the code

conclusion

React QQ group:788023830 —- React/Redux - Old underground hero

Front-end COMMUNICATION QQ group:249620372 —- FRONT - END - JS FRONT END

(Our mission is, for overtime, for baldness… , look up to the big guy), I hope friends to study together