如何在 React.js 中延迟 return 以从 JSON 加载数据

How to delay return in React.js for load data from JSON

到目前为止,我已经尝试了几种在互联网上找到的方法,但 none 都奏效了。我现在在代码中尝试了 setTimeout 和设置 isLoading。

至于加载数据,我确信它们显示正确,因为删除段落中的加载品牌后,数据在控制台中可见(更准确地说是在 React 'Components'附加)

这是 JSON 文件的样子:

[
   {
    id: 0,
    brand: "Lorem0",
    model: "Lorem",
    dealer: "Lorem",
    main_image: "Lorem",
    sections: [
        {
            id: 0,
            section_type: "",
            section_title: "Lorem",
            section_text: "Lorem Lorem Lorem Lorem Lorem",
            image_left: "Lorem1.png",
            image_center: null,
            image_right: null
        }
      ]
   },
   {
    id: 1,
    brand: "Lorem0",
    model: "Lorem",
    dealer: "Lorem",
    main_image: "Lorem",
    sections: [
        {
            id: 0,
            section_type: "",
            section_title: "Lorem",
            section_text: "Lorem Lorem Lorem Lorem Lorem",
            image_left: "Lorem1.png",
            image_center: null,
            image_right: null
        }
      ]
   },    
]

这是来自 App.js 的代码:

state = {
   isLoading: true,
}
carData = [];

componentDidMount() {
   fetch("/data.json")
     .then(response => response.json())
     .then(data => {
       this.setState({
         carData: data,
         isLoading: false
       })
     })
 }
 render() {
   return (
     <div className="App">
       {!this.state.isLoading && <p>{this.carData[1].brand}</p>}
     </div>
   );
 }

也许我犯了一个我看不到的错误,但在我看来一切都很好,但错误仍然出现。

TypeError: 无法读取未定义的 属性 'brand'

state = {
   isLoading: true,
   carData: [] // you should put the carData here.
}

componentDidMount() {
   fetch("/data.json")
     .then(response => response.json())
     .then(data => {
       this.setState({
         carData: data,
         isLoading: false
       })
     })
 }
 render() {
   return (
     <div className="App">
       {!this.state.isLoading && <p>{this.state.carData[1].brand}</p>}
     </div>
   );
 }

您正在将 data 存储在状态中,但您并未尝试从状态中加载数据。

试试下面的方法:-

state = {
   isLoading: true,
   carData: []  // initialize carData with blank array in state 
}


componentDidMount() {
   fetch("/data.json")
     .then(response => response.json())
     .then(data => {
       this.setState({
         carData: data,
         isLoading: false
       })
     })
 }
 render() {
   return (
     <div className="App">
       {!this.state.isLoading && <p>{this.state.carData[1].brand}</p>}   // use carData with this.state.carData
     </div>
   );
 }

您也可以使用可选链接

this.state.carData[1]?.brand

首先,将 carData 作为 属性 添加到状态对象。

state = {
   carData: []  // add carData
}

然后你可以删除 ìsLoading 属性 如果你像这样插入 brand 到 JSX。

render() {
   return (
     <div className="App">
       <p>{this.state.carData[1]?.brand}</p>
     </div>
   );
 }

?. 称为可选链接https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining