简体   繁体   English

使用 useEffect 和 useState 在 React JS 中出现无限循环错误

[英]Infinite loop error in React JS with useEffect and useState

First, I'd like to precise this is one of my first React projects so I'm quite uncomfortable with it, and especially when it comes to treating with APIs.首先,我想准确地说这是我的第一个 React 项目之一,所以我对它很不适应,尤其是在使用 API 处理时。

My goal here is to create a filter that updates the URL in the fetch so that I can ask the API details about movies, for example search movies that are exclusively Drama genre, by checking a checkbox.我的目标是创建一个过滤器,在 fetch 中更新 URL,以便我可以通过选中复选框询问有关电影的 API 详细信息,例如搜索专门为戏剧类型的电影。

My code is getting an infinite loop error and despite searching a lot through the net I couldn't find any help about my problem, so I came here to request your help haha.我的代码出现无限循环错误,尽管在网上搜索了很多,但我找不到任何关于我的问题的帮助,所以我来这里请求你的帮助哈哈。

Thank you so much in advance.非常感谢你。

function List() {
    const [movies, setMovies] = useState([])
    const [dbLink, setDbLink] = useState('')

    let genre = []

    useEffect(() => {
        fetch(dbLink)
            .then(response => response.json())
            .then(json => setMovies(json))
    }, [movies.results])

    const assembleLink = () => {
        const main = 'https://api.themoviedb.org/3/discover/movie?api_key='
        const apiKey = 'xxx'
        let genres = ''
        let genresComponent = ''

        if (genre != []) {
            genre.forEach(key => {
                genres = genres + key + ','
                console.log(genres)
            });
            genresComponent = '&with_genres=' + genres
        }

        setDbLink(main + apiKey + genresComponent)
        console.log(dbLink)
    }

    const addGenre = (genreID) => {
        genre.push(genreID)
        assembleLink()
        console.log("Changed!")
    }

    if (movies.results) {
        console.log(movies)
        console.log(movies.results)
    }

Using movies or any nested property of it as a dependency in an useEffect callback that updates that state will likely cause the render looping you see.使用movies或其任何嵌套属性作为useEffect回调中的依赖项,更新state可能会导致您看到的渲染循环。

useEffect(() => {
  fetch(dbLink)
    .then(response => response.json())
    .then(json => setMovies(json)) // <-- updates movies state
}, [movies.results]) // <-- movies state dependency

It seems like you should have a dependency on the dbLink state, that when it updates you fetch movies.似乎您应该依赖dbLink state,当它更新时您会获取电影。

useEffect(() => {
  fetch(dbLink)
    .then(response => response.json())
    .then(json => setMovies(json))
}, [dbLink])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM