鍍金池/ 問(wèn)答/HTML/ react 在componentWillMount方法中無(wú)法獲取數(shù)組類型的參數(shù)

react 在componentWillMount方法中無(wú)法獲取數(shù)組類型的參數(shù)

1.父組件向子組件傳值在componentWillMount()方法中console.log()只打印出了字符串?dāng)?shù)據(jù) 數(shù)組數(shù)據(jù)為長(zhǎng)度為0就是沒(méi)有數(shù)據(jù)

傳值的代碼
clipboard.png

子組件代碼
clipboard.png

頁(yè)面效果
可以看到數(shù)據(jù)都能被渲染出來(lái)確實(shí)傳值成功
clipboard.png

但是componentWillMount()打印books這個(gè)數(shù)據(jù)的時(shí)候卻是空值
clipboard.png

回答
編輯回答
糖果果

你這個(gè) booklist 數(shù)據(jù) 8成 是 ajax 或 fetch 獲取 的 數(shù)據(jù)。。。 你初始化 肯能 是空數(shù)組,所以才出現(xiàn) [], 當(dāng)獲取完數(shù)據(jù), 父組件 更改 子組件的 props, 造成 組件件更新, 就顯示出字來(lái)。
最簡(jiǎn)單的方法, 你在 render 里面 打印 數(shù)組。 看看是不是 出兩次。

2018年9月4日 18:30
編輯回答
老梗

你這個(gè)books的數(shù)據(jù)是不是異步獲取的,如果是異步獲取的話componentWillMount的時(shí)候可能確實(shí)還沒(méi)有數(shù)據(jù),要等取得數(shù)據(jù)之后會(huì)觸發(fā)子組件的更新,可以在componentWillReceiveProps里打印看看

2018年7月24日 05:48
編輯回答
不將就

父組件觸發(fā)子組件componentWillReceiveProps

2018年3月19日 15:51
編輯回答
有點(diǎn)壞

那你在父組件中看看是否有值

2017年10月29日 00:06
編輯回答
雨萌萌

里面的 this.state.book1可能是異步改變的,
子組件首次實(shí)例化是,沒(méi)獲取到 books值,componentWillMount里面就是空的
存在期 組件已存在時(shí)的狀態(tài)改變,也就是 book1的值獲取到了
依次觸發(fā)

   componentWillReceiveProps ->
   shouldComponentUpdate ->
   componentWillUpdate ->
   render ->
   componentDidUpdate

可以在上面的幾個(gè)周期函數(shù)打印出來(lái)看看

2018年7月27日 00:58