我不知道如何指定標題。傳遞給子組件的屬性被默認記錄爲false
這裏是我的問題:
我有向下傳遞它的默認狀態屬性,一些子組件的父組件。
其中一個默認狀態被傳遞如下:
<FriendButton is_friend={this.props.is_friend} />
FriendButton是在父母的孩子組成部分,這就是爲什麼它是this.props這裏
因此,這是什麼我試圖傳遞給<FriendButton />
:
this.props.is_friend == true
所以現在我<FriendButton />
組件I W內螞蟻來處理這個價值。奇怪的是,它被記錄爲「false
」。
這裏是我的簡單的代碼來檢查:
import React from 'react';
class FriendButton extends React.Component {
constructor(){
super();
this.state = {
friend_status: ""
}
}
componentWillMount(e){
console.log("Friend status at friend button: ",this.props);
if(this.props.is_friend){
this.setState({
friend_status: "Friend"
});
}else{
this.setState({
friend_status: "Friend request"
});
}
}
render() {
return(
<button className="friend-request-button">{this.state.friend_status == "Friend" ? <i className="fa fa-check"></i> : <i className="fa fa-user-plus"></i>}{this.state.friend_status}</button>
);
}
}
export default FriendButton;
現在你可以看到我日誌中的componentWillMount()
的props
和LOGG,我得到的是:Friend status at friend button: Object {is_friend: false}
當我檢查我的GoogleChrome React Tools中的組件我可以清楚地看到,該屬性設置爲true
,如下圖所示。
這從來沒有發生在我面前 - 任何想法我會在這裏失去了?
查看componentWillMount()的文檔:https://facebook.github.io/react/docs/component-specs.html更具體地說'在發生初始渲染之前立即調用',導致我認爲您的組件在console.log時尚未從父組件收到實際的道具。相反,你應該能夠將道具傳遞給你的構造函數並在那裏設置狀態。 – Thomas
我會盡力的。我檢查了componentWillReceiveProps(),在那裏我可以記錄正確的道具值 –
@Thomas Ok使用cunstructor函數直接設置狀態this.props不起作用。道具不可用於構造函數中的組件。我已經設法讓它工作。看到我的回答 –