2017-07-27 70 views
0

我目前正在嘗試自我教導React,此刻我正在使用codepen,我正在嘗試的是從靜態JSON創建一個簡單的用戶配置文件。學習React概念驗證

我想從某人得到的確認是我的理解在我進步之前是正確的。

我的理解是React應用程序是由狀態對象驅動的?這個狀態對象的元素可以傳遞給組件並且它們變成道具(它們是隻讀的?)。如果我可以在狀態中使用某些東西,它會反映在組件中使用的任何道具上?

這是我迄今爲止的概念驗證,它基本上是從狀態獲取和頭像URL,並創建一個非常簡單的頭像組件。

/* 
* A simple React component 
*/ 

const user = { 
    "id": 1, 
    "first_name": "Anjela", 
    "last_name": "Frow", 
    "email": "[email protected]", 
    "dob": "1987-07-09", 
    "gender": "Female", 
    "avatar": "https://robohash.org/quaslaboriosamvoluptas.jpg?size=50x50&set=set1" 
} 

class Application extends React.Component { 
    constructor() { 
    super(); 
    this.state = { 
     user:user 
    } 
    } 

    render() { 
    return (<Profile user={this.state.user} />); 
    } 
} 

class Profile extends React.Component { 
    render() { 
    return (
     <Avatar image={this.props.user.avatar} /> 
    ) 
    } 
} 

class Avatar extends React.Component { 
    render() { 
    return (
     <div class="avatar"> 
     <img src={this.props.image} /> 
     </div> 
    ) 
    } 
} 

/* 
* Render the above component into the div#app 
*/ 
React.render(<Application />, document.getElementById('app')); 

https://codepen.io/87Development/pen/XabxGX?editors=1010

+0

我會建議你檢查[** DOC **](https://facebook.github.io/react/docs/hello-world.html),它會涵蓋所有這些細節。 –

+0

這不是一個codereview的問題嗎?反應可以由國家或道具驅動,這就是你的假設正確的地方:) – Icepickle

+0

是的。你的理解是正確的。您可以將狀態作爲道具傳遞給其他組件,並且只有在您更新父組件的狀態時道具纔會更新 –

回答

1

我建議嘗試一些東西,看看事情如何「反應」。 例如,添加一個更新user.avatar的按鈕。

onClick() { 
    this.setState({user: Object.assign({}, this.state.user, {avatar: 'new'})}); 
} 

state.user的特此設置爲一個完全不同的對象引用,這將導致一個重新呈現。

你應該看到更新的<Avatar />,因爲它收到它的新道具。

正如您已經提到的props是隻讀的。 state也應該認爲是隻讀的,永遠不要直接更新,但始終通過一個setState()

1

是的你是對的。

儘管在你的代碼,它不是很實用,「純」要做到這一點:

return (<Profile user={this.state.user} />); 

,就是因爲它意味着你Profile需要使用一個完整的用戶對象,即使它實際上只需要一張圖片。因此,對於可重用性的目的和清晰,你可以聲明,而化身道具:

return (<Profile avatar={this.state.user.avatar} />); 

有了這個,你可以使用Profile組件,即使你只有一個化身鏈接。

這也意味着你應該爲每一個你想傳遞的用戶屬性添加一個道具。