【问题标题】:how to use react fetch() with useEffect hook and map the fetched data如何使用带有 useEffect 钩子的 react fetch() 并映射获取的数据
【发布时间】:2021-02-21 20:20:32
【问题描述】:

尝试使用 useEffect 钩子在前端获取 api 数据,

我可以通过控制台记录数据,但无法以某种方式对其进行映射

新反应

console output

function SlugBook() {
    // let {slug} = useParams(),
    const [state, setState] = useState([])
    
    useEffect(() => {
        fetch("http://127.0.0.1:8000/app/reviews/",{CSRF_TOKEN....}
            )
            .then(response => response.json()) 
            .then(data => console.log(data)) -->works fine
            .then(data => setState(data)); --> not sure
        
           })

         return (
               <p>
            {state.map( d => (<li>{d}</li>))} ---> error code ()
               </p>
            )
            }
 export default SlugBook

【问题讨论】:

  • data =&gt; console.log(data) 是无效返回,因此您将 undefined 返回到下一个 then-able,即您是 setState(undefined)。您的 useEffect 挂钩缺少依赖项,因此任何状态更新都会触发渲染循环。

标签: reactjs react-hooks frontend fetch


【解决方案1】:

两个问题:

  1. 您需要在第二个then 中设置您的状态,如下所示:
    useEffect(() => {
        fetch("http://127.0.0.1:8000/app/reviews/",{
            credentials: 'include',
            method: 'GET',
            mode: 'same-origin',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'X-CSRFToken': CSRF_TOKEN
            }})
            .then(response => response.json()) 
            .then(data => setState(data))
    })
  1. 您需要在useRef 中使用依赖数组,否则您将获得无限的重新渲染。所以改成:
    useEffect(() => {
        fetch("http://127.0.0.1:8000/app/reviews/",{
            credentials: 'include',
            method: 'GET',
            mode: 'same-origin',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'X-CSRFToken': CSRF_TOKEN
            }})
            .then(response => response.json()) 
            .then(data => console.log(data)) -->works fine
            .then(data => setState(data)); --> not sure

        
    }, [])

将依赖数组设置为空数组[] 将确保您的useEffect 在第一次渲染时只运行一次fetch

【讨论】:

  • @VishalGupta 不确定什么是缩小反应错误。
猜你喜欢
  • 2020-09-14
  • 1970-01-01
  • 2021-02-06
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2022-01-16
相关资源
最近更新 更多