【问题标题】:How to update state array fetched from API in React Hooks?如何更新从 React Hooks 中的 API 获取的状态数组?
【发布时间】:2021-01-09 13:47:22
【问题描述】:

我正在从 Studio Ghibli API 获取数据,并且能够成功获取数据,设置对象的状态数组并将其呈现在我的演示组件中。但是,我正在尝试创建一个函数,它将向状态数组中的每个对象添加新属性“关键字”。问题是当我尝试复制状态数组以在我的 createKeywords 函数中对其进行操作时,返回的副本为空,并且在设置后我无法对其进行操作。

这是相关代码:

  const baseUrl = 'https://ghibliapi.herokuapp.com/'
  const [hasError, setErrors] = useState(false)
  const [movies, setMovies] = useState([])

  useEffect(() => {
    fetch(baseUrl + 'films')
      .then((res) => res.json())
      .then((res) => {
        console.log(res);
        setMovies(res)
        createKeywords()
      })
      .catch(err => setErrors(true));
  }, [])

  const createKeywords = () => {
    const moviesWithKeywords = [...movies]
    moviesWithKeywords.forEach(function(movie){
      movie.keyword = 'castle'
    }); 
    setMovies(moviesWithKeywords)
}

如果我不调用 createKeywords 函数,一切正常,但显然复制和设置新电影状态会产生问题。我尝试在 useEffect 中添加 [movies] 而不是空数组,这有效,但随后 useEffect 无限期运行。提前谢谢你,React 不是我的强项!

【问题讨论】:

    标签: reactjs react-hooks fetch use-effect


    【解决方案1】:

    解决方案似乎不是很明显。在某些情况下,setMovies(通常设置状态)是异步操作,这意味着即使您 setMovies,movies 变量的更新速度也不会很快,因此您已经在执行 createKeawords 函数。这意味着在关键字函数中,movies 变量没有机会足够快地更新。我建议在 createKeywords 中将 res 作为参数传递,并使用此变量将数组复制到 moviesWithKeywords

    State Updates May Be Asynchronous部分下查看这里

    所以做这样的事情:

      const baseUrl = 'https://ghibliapi.herokuapp.com/'
      const [hasError, setErrors] = useState(false)
      const [movies, setMovies] = useState([])
    
      useEffect(() => {
        fetch(baseUrl + 'films')
          .then((res) => res.json())
          .then((res) => {
            console.log(res);
            setMovies(res)
            createKeywords(res)
          })
          .catch(err => setErrors(true));
      }, [])
    
      const createKeywords = (movies) => {
        const moviesWithKeywords = [...movies]
        moviesWithKeywords.forEach(function(movie){
          movie.keyword = 'castle'
        }); 
        setMovies(moviesWithKeywords)
    }
    

    【讨论】:

    • 谢谢!这对我有用,我现在使用 res 在 createKeywords 中设置电影状态,而不是在 useEffect 中设置它。
    • 值得阅读我发布的链接。你也能接受答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多