我想測試渲染列表組件從一個JSON對象調用與提取,但是我懷疑渲染是在JSON返回之前調用,因爲我得到一個未定義的錯誤。注意debug alert()獲取值,但渲染在undefined時已經出錯。我該如何處理?數據獲取後有沒有辦法調用渲染函數?或者我可以如何獲得數據以'?'呈現然後在數據到達時更新?請注意我的if(!object)doesn; t作爲內聯包裝函數調用 - 爲什麼不 - 或者更不重要的是如何執行此操作?對於begginer問題抱歉 - 我懷疑我打算使用數據框架來爲顯示反應提供數據,但我想用較少的框架開始學習並獲得基礎知識。非常感謝! - 代碼:react.js的初學者 - 從稍後更新狀態的渲染組件
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class ItemLister extends React.Component {
constructor(props) {
super(props);
this.state = { items: [] };
}
componentDidMount() {
let url = "http://localhost:8888";
let iterator = fetch(url, {method: 'GET'});
iterator
.then(response => {
//console.log('sss', response)
return response.json();
})
.then(post => {
//console.log(post)
this.state.items = post;
alert(this.state.items.users[3].firstname);
});
}
output(object){
if (!object){
return '?';
}else{
return object;
}
}
render() {
return(
<div>
<div>Items:</div>
<div>{this.output(this.state.items.users[3].firstname)}</div>
</div>
);
}
}
export default ItemLister;
是的,這是React或其他此類框架的基本內容。當沒有數據和狀態發生變化時,您將呈現一個佔位符/加載/無論什麼時候組件將再次呈現並且您將呈現實際數據。它不工作的原因是因爲你試圖訪問'this.state.items.users ...'並且它不存在,所以它甚至不能訪問該函數。 –