Conversation
| return rows | ||
| } | ||
|
|
||
| // componentDidMount()不是在render後才執行嗎,為什麼不把this.setState()放在componentWillMount呢? |
There was a problem hiding this comment.
這部分可以參考這篇喔
https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/
簡單來說主要有兩個原因
- 在等待 fetch callback 的時候是是沒有資料的,如果沒有正確設定 state 空狀態就會造成crash,可以避免本地測試的時候網路太快,瞬間載完資料沒有測到的情況
- 在 React 有 serverside render 所以 WillMount 會被叫兩次,但是 RN 沒有這困擾,所以大家放 DidMount 也已經習慣且變成慣例了
| const p1 = new Promise((resolve, reject) => { | ||
| this.setState({ | ||
| page: this.state.page + 1 | ||
| }) |
There was a problem hiding this comment.
setState 其實是有自己的 callback 的
this.setState({
page: this.state.page + 1
}, () => {
// 這裡是 setState 完成會呼叫的 callback
})
| p1.then(async(newPage) => { | ||
| try{ | ||
| this.setState({ | ||
| data: this.state.data.concat(await this.getData(this.state.page)) //關鍵在於必須先取得非同步getData()的資料 |
There was a problem hiding this comment.
這邊這樣子資料是不會更新的,因為 concat 是用參考的方式,不是新的 array,這樣下次 render 值又會變回原來的,要使用這樣
const data = await this.getData(this.state.page);
this.setState({
data: [...this.state.data, data]
})
來合併
There was a problem hiding this comment.
我打data: [...this.state.data, data]會變成[ { key: 10,
name: 'Bowie Wathey',
job: 'Information Systems Manager',
avatar: 'https://robohash.org/eaquenobisenim.png?size=150x150&set=set1' }, [ { key: 11,
name: 'Benito O'Heaney',
job: 'Chemical Engineer',
avatar: 'https://robohash.org/autemeosquia.png?size=150x150&set=set1'}, ... ] ]。
data似乎也要加上... ,把新加入data的value迭代出來結果才會正確。像這樣:data: [...this.state.data, ...data],不知是否有錯?
| // 滾動載入資料 | ||
| } | ||
| return responseJson; | ||
| // return responseJson; 應該是要return data吧? |
There was a problem hiding this comment.
這邊我沒注意到XDD
其實本意是要在 if 裡面直接做 set data 的動作 不用 return 東西
練習三的下拉更新功能雖已完成,但this.state.data在console.log最多只能顯示到第26筆資料