Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

一个react的hooks的问题

useEffect(() => {

console.log(666)

}, [a,b]}

a和b同时改变的话,666会打印两次,
这种情况怎么避免呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

摘抄自另一个问题的回答:https://ostack.cn/q/10...

import React, { useState, useEffect, useRef } from 'react';

const One = _ => {
  const [a, setA] = useState(0);
  const [b, setB] = useState(0);
  const ref = useRef({ a, b });

  useEffect(() => {
    let { a: prevA, b: prevB } = ref.current;
    console.log('更新前:', prevA, prevB);
    console.log('更新后:', a, b);
    
    //a 和 b 同时改变的时候不执行
    if (prevA !== a && prevB !== b) {
      return
    }
    console.log(666);
    ref.current = { a, b };
  }, [a, b]);

  return (
    <>
      <h1>{a + b}</h1>
      <button onClick={_ => setA(d => d + 1)}>Chang A</button>
      <button onClick={_ => setB(d => d + 1)}>Chang B</button>
    </>
  );
};

export default One;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...