【问题标题】:useEffect Hook in React causing infinite loopsReact 中的 useEffect Hook 导致无限循环
【发布时间】:2021-02-19 03:31:57
【问题描述】:

我是 React Hooks 的新手。我不知道为什么它会导致无限循环。我在依赖数组中指定了 commentArr,它只更新一次,在组件为第一次。我读到将依赖数组留空只会运行一次 useEffect。它解决了我的问题(无限循环),但是 React 给了我这个警告。

Line 31:7:  React Hook useEffect has a missing dependency: 'commentArr'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

这是我使用 Hooks 的组件。如何在没有任何警告的情况下解决无限循环问题?

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

import Footer from './Footer'
import Navigation from './Navigation'
import styles from "../assets/css/calc.module.css"
import Comment from './Comment'
import PostComment from './PostComment'
import assets from '../assets'
import axios from "../axiosConfig"
import AnsModal from './AnsModal'

function Calc(props) {

    const [commentArr, setCommentArr] = useState(null);

    useEffect(() => {
        axios.get('/comments.json')
            .then(res => {
                // for transforming object of objects into array of objects
                let allComments = []
                for (let key in res.data) {
                    allComments.push({
                        id: key,
                        ...res.data[key]
                    })
                }
                setCommentArr(allComments)
                console.log(commentArr);
            })
            .catch(err => console.log(err))
    },[commentArr])
    return (
    <>
        <div className="container bg-white shadow text-muted p-4">
            <Navigation />
            <div className="row d-flex justify-content-center m-2">
                <div className="col-md-8 col-12 text-justify">
                    Let this calculator do the heavy lifting.This formula helps you to calculate equivalent worth (Future Worth, F) given the values of Present Worth (P),
                    interest rate per year (effective interest rate) and time (investment duration).
                </div>
            </div>


            <div className="row">
                <div className="col-md-6 col-12">
                    <img src={assets[props.location.state.imagePath]} alt="image1" className={styles.image}/>
                </div>
                <div className="col-md-6 col-12">
                    <h4>Fill in the values.And get answers in seconds.</h4>
                    <hr style={{background: '#55b8cf', height: '6px'}}/>
                    <div className="form-group">
                        <label htmlFor="firstInput">{props.location.state.sum} value</label>
                        <input type="text"  id="firstInput" className="form-control" placeholder="e.g. 10000"/>
                    </div>
                    <div className="form-group">
                        <label htmlFor="secondInput">i value</label>
                        <input type="text" id="secondInput" className="form-control" placeholder="e.g. type 0.1 for 10%"/>
                    </div>
                    <div className="form-group">
                        <label htmlFor="thirdInput">n value</label>
                        <input type="text" id="thirdInput" className="form-control" placeholder="e.g. 5"/>
                    </div>
                    <div className="text-center">
                        <AnsModal />
                    </div>
                </div>
            </div>
            <h4>Comments</h4>
            <hr style={{background: '#55b8cf'}}/>

            <div className="row">
                <div className="col-md-6 col-12">
                    <Comment />
                    <Comment />
                    <Comment />
                    
                </div>
                <div className="col-md-6 col-12">
                    <PostComment />
                </div>
            </div>
            <hr style={{background: '#55b8cf'}}/>
            <Footer />
            
        </div>
        
    </>
    )
}
export default Calc;

【问题讨论】:

  • 您可以在钩子的第一行添加一个条件,例如if(commentArr.length) return;

标签: reactjs redux react-hooks


【解决方案1】:

在您编写的这段代码中:

  useEffect(() => {
    axios.get('/comments.json')
        .then(res => {
            // for transforming object of objects into array of objects
            let allComments = []
            for (let key in res.data) {
                allComments.push({
                    id: key,
                    ...res.data[key]
                })
            }
            setCommentArr(allComments)
            console.log(commentArr);
        })
        .catch(err => console.log(err))
},[commentArr])

这个console.log(commentArr); 提示作为依赖做出反应。而只是使用这个:

   useEffect(() => {
    axios.get('/comments.json')
        .then(res => {
            // for transforming object of objects into array of objects
            let allComments = []
            for (let key in res.data) {
                allComments.push({
                    id: key,
                    ...res.data[key]
                })
            }
            setCommentArr(allComments)
  
        })
        .catch(err => console.log(err))
},[]);
 console.log(commentArr);

【讨论】:

  • OP 提到的警告中的原因。
  • @Jai 它只会引起警告,因为它们在效果内是console.log(commentArr);。将其移出后,它不应再发出警告。
  • @Farhad 它像魅力一样工作,谢谢你是如何发现控制台日志导致的?你能给我推荐一些不错的文档吗?最后一个问题,将依赖数组留空会导致以后出现任何问题吗?
猜你喜欢
  • 2020-09-06
  • 2021-11-01
  • 2021-02-13
  • 2021-01-22
  • 2020-08-27
  • 2020-11-16
相关资源
最近更新 更多