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
1.2k views
in Technique[技术] by (71.8m points)

useEffect死循环问题

const {visible} = props;
const [dateRange, setDateRange] = useState([moment(), moment()]);

    useEffect(() => {
        const getData = async () => {
            const res = await fetch({ start: dateRange[0].valueOf(), end: dateRange[1].valueOf()});
        }
        if(visible){
            // 每次出现的时候都重置dateRange值
            setInputValue([moment(),moment()])
            // 每次出现的时候都请求接口
            getData()
        }
    }, [visible, dateRange]);

    const handleInputChange = (value) => {
        setDateRange(value);
    }
    return (
        <div style={{ display: 'flex' }}>
            <DateRange value={dateRange} onChange={handleInputChange}></DateRange>
        </div>
    );

由于每次dateRange都是新数组,导致每次dateRange都是新的,useEffect会死循环,如何解决?


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

1 Answer

0 votes
by (71.8m points)

依赖项改成直接依赖dateRange的元素

const {visible} = props;
const [dateRange, setDateRange] = useState([moment(), moment()]);

    useEffect(() => {
        const getData = async () => {
            const res = await fetch({ start: dateRange[0].valueOf(), end: dateRange[1].valueOf()});
        }
        if(visible){
            // 每次出现的时候都重置dateRange值
            setInputValue([moment(),moment()])
            // 每次出现的时候都请求接口
            getData()
        }
    }, [visible, dateRange[0], dateRange[1]);

    const handleInputChange = (value) => {
        setDateRange(value);
    }
    return (
        <div style={{ display: 'flex' }}>
            <DateRange value={dateRange} onChange={handleInputChange}></DateRange>
        </div>
    );

PS:
看代码逻辑useEffect本质只依赖变量visible,代码可以调整为:

const {visible} = props;
const [dateRange, setDateRange] = useState([moment(), moment()]);

const getData = async () => {
            const res = await fetch({ start: dateRange[0].valueOf(), end: dateRange[1].valueOf()});
        }
        
    useEffect(() => {               
        if(visible){
            // 每次出现的时候都重置dateRange值
            setInputValue([moment(),moment()])
            // 每次出现的时候都请求接口
            getData()
        }
    }, [visible]);

    const handleInputChange = (value) => {
        setDateRange(value);
    }
    return (
        <div style={{ display: 'flex' }}>
            <DateRange value={dateRange} onChange={handleInputChange}></DateRange>
        </div>
    );

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

...