【问题标题】:Can't set JSON data in react state无法在反应状态下设置 JSON 数据
【发布时间】:2021-06-06 08:13:39
【问题描述】:

所以我试图将一个 JSON 对象设置为一个状态,但它不断地给出一个空对象。不知道为什么。

import React, {useState} from 'react'

const MainApp = () => {

    const [products, setProducts] = useState({})
    const url = "http://localhost:5000/products"

    fetch(url)
        .then(res => res.json())
        .then(res => setProducts(res))
        .catch(err => { console.log(err) })
         
        console.log(products) //this gives an empty object

}

export default MainApp  

这是 http://localhost:5000/products 中的输出

[
  {
    "id": "trYl7JYATH0",
    "description": "Test caption",
    "imgThumb": "test.jpg",
    "img": "test.jpg",
    "link": "test.jpg",
    "userId": "X0ygkSu4Sxo",
    "userName": "user",
    "userLink": "https://unsplash.com/@user",
    "tags": [
      "building",
      "architecture",
      "corner",
      "black",
      "dark",
      "balcony",
      "night"
    ]
  }
]

【问题讨论】:

  • res.json() 返回什么?
  • fetch(url) 是异步的。您开始获取,但是当您的状态仍然为空时,您的程序继续执行下一条语句console.log()。您可以谷歌 async/await fetch 进一步阅读

标签: javascript node.js json reactjs


【解决方案1】:

您不应该在主函数中发出网络请求。 React 提供了一个钩子,叫做useEffect

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

const MainApp = () => {

  const [products, setProducts] = useState([]) //API returning array
  const url = "http://localhost:5000/products"

  useEffect(() => {
    // Update the document title using the browser API
    fetch(url)
      .then(res => res.json())
      .then(res => setProducts(res))
      .catch(err => {
        console.log(err)
      })
  }, []); //This function will run at the last, when all componenets rendered in browser
}

ReactDOM.render( <
  MainApp / > ,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

【讨论】:

  • 你的答案不正确。您将useEffect 包裹在fetchDataFromServer 中,它应该是相反的
  • 哦,明白了。我会修复
  • 仍然不正确。 fetchDataFromServer 未定义为 const
猜你喜欢
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 2020-10-20
  • 2021-04-01
  • 2019-12-27
相关资源
最近更新 更多