2016-01-17 52 views
0

我不知道如何指定標題。傳遞給子組件的屬性被默認記錄爲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,如下圖所示。

enter image description here

這從來沒有發生在我面前 - 任何想法我會在這裏失去了?

+0

查看componentWillMount()的文檔:https://facebook.github.io/react/docs/component-specs.html更具體地說'在發生初始渲染之前立即調用',導致我認爲您的組件在console.log時尚未從父組件收到實際的道具。相反,你應該能夠將道具傳遞給你的構造函數並在那裏設置狀態。 – Thomas

+0

我會盡力的。我檢查了componentWillReceiveProps(),在那裏我可以記錄正確的道具值 –

+0

@Thomas Ok使用cunstructor函數直接設置狀態this.props不起作用。道具不可用於構造函數中的組件。我已經設法讓它工作。看到我的回答 –

回答

0

由於componentWillMount()被激發得太早,無法接收正確的屬性值,因此無法正確更新狀態。使用componentWillReceiveProps(props){}生命週期使我能夠實現我想要的。

這裏是我如何使用該功能的示例代碼:

componentWillReceiveProps(props){ 
    console.log("Props: ", props); 
    if(props){ 
     var friend_status = "Friend"; 
    }else{ 
     var friend_status = "Friend request"; 
    } 
    this.setState({ 
     is_friend: props, 
     friend_status: friend_status 
    }); 
    } 

這爲我工作。

+0

我建議使用條件三元運算符而不是'if/else'。這會縮短上面的'var friends_status ===道具? '朋友':'好友請求';'。這是(至少對我來說),更可讀,佔用更少的空間。在這裏閱讀更多關於它們的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator。 – Thomas