Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

React Hook useEffect has a missing dependency

组件

const Demo: React.FC<FormProps> = ({ visible, value, onChange }) => {
    const [list, setList] = useState<any>([
        { id: 1, checked: false, },
        { id: 2, checked: false, },
        { id: 3, checked: false, },
        { id: 4, checked: false, },
        { id: 5, checked: false, },
    ]);

    useEffect(() => {
        // visible变化的时候,根据value重置checked的id值
        const newList = list.map((item: any) => {
            return { ...item, checked: value === item.id };
        })
        setList(newList);
    }, [visible, list]);// 这里加上list会死循环,不加list会有lint提示

    const handleItemClick = (item: any) => {
        const newList = list.map((_item: any) => ({ ..._item, checked: item.id === _item.id }));
        setList(newList);
        onChange(item);
    }
    return (
        <div style={{ display: 'flex' }}>
            {
                list.map((item: any) => <p onClick={() => handleItemClick(item)} style={{ width: 100, color: '#fff', background: item.checked ? 'red' : 'blue' }}>{item.id}</p>)
            }
        </div>
    );
};

页面

const DemoPage: React.FC<FormProps> = () => {
  const [visible, setVisible] = useState(false);
  const [value, setValue] = useState(1);
  const handleVisibleChange = () => {
    setVisible(!visible);
    if (visible) {// 每次visible为true时,重置value值
      setValue(1);
    }
  }
  const handleDemoChange = (item) => {
    setValue(item.id)
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <span>visible:{visible.toString()}</span>
      <Button onClick={handleVisibleChange}>change visible</Button>
      <Demo value={value} visible={visible} onChange={handleDemoChange} ></Demo>
    </div>
  );
};

useEffect加上依赖会死循环,不加依赖会有lint提示,怎么破?


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

1 Reply

0 votes
by (71.8m points)

有2种方法 :
1、setList(newList);前对比手动对比list,如果一样不执行setList
2、checked这个状态单独维护一个变量


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...