反应 useEffect 获取 - 类型错误?

问题描述 投票:0回答:2

这段代码有什么问题..
在控制台上一切正常,但在我尝试使用

setData(result)
获取数据到 div 之后 我有一个很大的脂肪错误:

×
Unhandled Rejection (TypeError): setData is not a function
(anonymous function)
C:/blog/src/components/BlogPosts.js:19
  16 |        .then((res) => res.json())
  17 |        .then((result) => {
  18 |          console.log(result)
> 19 |          setData(result)
     | ^  20 |        })
  21 |    }
  22 | 
import { useState, useEffect } from 'react'
import styles from './BlogPosts.module.css'


const BlogPosts = () => {
  const { data, setData } = useState([])

  useEffect(() => {
    const fetchData = async () => {
      fetch('https://jsonplaceholder.typicode.com/posts')
        .then((res) => res.json())
        .then((result) => {
          console.log(result)
          setData(result)
        })
    }

    fetchData()
  }, [])

  return (
    <section className={styles.posts}>
      {/* <div>
        {data.map((x) => {
          return <div key={x.id}>{x.title}</div>
        })}
      </div> */}
    </section>
  )
}

export default BlogPosts
reactjs react-hooks fetch-api
2个回答
3
投票

问题就在这里:

  const { data, setData } = useState()

useState()钩子返回一个数组,所以你应该解构一个数组

  const [ data, setData ] = useState()

P.S,将状态初始化为空数组并没有什么坏处(与现在的无/未定义相比)

const [ data, setData ] = useState([])

您这样做是因为在您注释掉的代码中,您尝试使用map()方法,这是一种数组方法。


1
投票
 const fetchData = async () => {
      let res = null;
      fetch('https://jsonplaceholder.typicode.com/posts')
        .then((res) => res.json())
        .then((result) => {
          console.log(result)
          res = result;
        })
      return await res;
    }
useEffect(async() => {
   const data = await fetchData();
   setData(data);
  }, [])
© www.soinside.com 2019 - 2024. All rights reserved.