[英]Can't set JSON data in react state
所以我试图将 JSON object 设置为 state 但它不断给出一个空的 ZA8CFDE6331149EB2AC96B8B 想不通为什么。
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 中的 output
[
{
"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"
]
}
]
您不应该在主 function 中发出网络请求。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.