[英]Rendering data, fetched from an API in react-native
我正在使用 React-Native 並且在將數據從 API render
到render
函數時遇到問題。 我正在運行 node JS 並在一端表達從 SQL 數據庫中提取一些數據。 這將返回如下所示的 JSON:
{"routines":[{"routine_id":1,"name":"Morning Routine","start_time":"2020-03-09T14:24:38.000Z","end_time":"2020-03-09T15:24:44.000Z","is_approved":0}]}
我想遍歷routines
鍵並將每個routine
打印為 React 中的組件。 我並不關心使用什么類型的組件,我只想獲取數據。 我嘗試了幾種方法:
方法 1:將componentDidMount
與fetch
一起使用:
constructor() {
super();
this.state = { routines: {} }
}
componentDidMount() {
fetch('http://localhost:3000/routines')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.then( routines => {
this.setState({routines: routines});
})
.catch( error => {
console.error(error);
});
}
render() {
console.log(this.state)
盡管代碼的then(routines
部分返回了正確的數據,但this.state
render
this.state
記錄一個空對象。
方法 2:將所有內容放入componentDidMount
async componentDidMount() {
const response = await fetch("http://localhost:3000/routines")
const json = await response.json()
console.log('json');
console.log(json);
const routines = json.routines
this.setState({routines})
}
同樣,在記錄從componentDidMount
返回的 json 確實返回有效數據時,在render
記錄狀態不會產生任何結果。
在render
方法中,我也嘗試過:
const { routines } = this.state;
並且routines
顯示為未定義。
方法三:直接調用函數設置狀態。
constructor() {
super();
this.state = { routines: this.fetchData() }
}
這最終會返回一些奇怪的數據:
{"routines": {"_40": 0, "_55": null, "_65": 0, "_72": null}}
我假設這是因為本機反應不希望我這樣做。
我只想要一種從 API 獲取數據並在render
顯示該數據的簡單方法。 我已經瀏覽了大約四個教程,所有教程都以未定義或對象設置為render
方法的構造函數中的默認值結束。 我要瘋了嗎? 感覺這在某種程度上是不可能的..?
由於 fetch 是一個異步任務, this.setState({routines})
在執行render()
之后設置了數據this.setState({routines})
。 您可以在設置this.setState({routines})
后執行this.forceUpdate()
this.setState({routines})
。 這將在設置數據時重新執行render()
。
請參閱: https : //reactjs.org/docs/react-component.html#forceupdate
你做的一切都是正確的,只需在render
使用狀態,你就會看到更新。
constructor() {
super();
this.state = { routines: [] }
}
render() {
const { routines } = this.state
return (
<View>
{routines.map(item => <Text>{item.name}</Text>)}
</View>
)
}
這可能是因為 fetch 調用是異步的,並且您的渲染方法可能會在 api 調用加載之前嘗試使用它,所以您的 componentDidMount 應該像
componentDidMount() {
this.setState({routines:null})
//fire an api call
fetch('http://localhost:3000/routines')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.then( routines => {
this.setState({routines: routines});
})
.catch( error => {
console.error(error);
});
}
現在在您的渲染函數中,您應該首先確認例程不為空並且具有一些有效值,例如
render(){
if(this.state.routines !==null){
//your code to render component
}else{
//your loading or error message
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.