編輯:我重寫了這個問題,以澄清我後 - 謝謝你的迴應迄今爲止幫助我磨練它的人。在React中管理嵌套狀態的好方法
我想了解如何在React中最好地管理複雜的嵌套狀態,同時還限制內容未發生更改的組件的調用次數render()
。
作爲背景:
假設我有狀態,在這樣一個對象都「作者」和「出版物」:
{
'authors' : {
234 : {
'name' : 'Alice Ames',
'bio' : 'Alice is the author of over ...',
'profile_pic' : 'http://....'
},
794 : {
'name' : 'Bob Blake',
'bio' : 'Hailing from parts unknown, Bob...',
'profile_pic' : 'http://....'
},
...more authors...
},
'publications' : {
539 : {
'title' : 'Short Story Vol. 2',
'author_ids' : [ 234, 999, 220 ]
},
93 : {
'title' : 'Mastering Fly Fishing',
'author_ids' : [ 234 ]
},
...more publications...
}
}
在這個人爲的例子國家主要有兩個方面,通過訪問authors
和publications
鍵。
authors
鍵導致鍵入作者ID的對象,這會導致包含某些作者數據的對象。
publications
鍵導致在具有一些發佈數據的發佈的ID和作者數組上鍵入的對象。
假設我的狀態是一個App
組件通過類似以下的僞JSX子組件:
...
<App>
<AuthorList authors={this.state.authors} />
<PublicationList authors={this.state.authors} publications={this.state.publications} />
</App>
...
...
class AuthorList extends React.Component {
render() {
let authors = this.props.authors;
return (
<div>
{ Object.keys(authors).map((author_id) => {
return <Author author={authors[author_id]} />;
}
</div>
);
}
}
...
...
class PublicationList extends React.Component {
render() {
let publications = this.props.publications;
let authors = this.props.authors;
return (
<div>
{ Object.keys(publications).map((publication_id) => {
return <Publication publication={publications[publication_id]} authors=authors />;
}
</div>
);
}
}
...
假設AuthorList
有一堆孩子Author
組件,並PublicationList
有一堆孩子Publication
組件,這些組件使這些東西的實際內容。
這裏是我的問題:假設我想更新bio
對於給定的作家,但我不希望render()
被稱爲所有Author
和Publication
對象,其內容並沒有改變。
從這樣的回答:
ReactJS - Does render get called any time "setState" is called?
一個陣營組件的render()
功能將被調用任何時候的狀態,或任何其母公司,變化的狀態 - 無論該狀態變化是否有什麼使用該組件的道具。這個行爲可以用shouldComponentUpdate來改變。
人們如何處理像上面這樣複雜的狀態 - 它看起來好像在每個狀態上調用大量組件的render()方法都是一個很好的解決方案(即使生成的渲染對象是相同的並且沒有變化發生在實際的DOM上)。
嗯...不知道爲什麼你會回答你的問題,這與我所說的幾乎相同。 – jpdelatorre
因爲這兩個答案實際上並不相同。您的結果是每當State.authors中的任何狀態發生更改時,AuthorList的所有Author子級都會重新呈現。我有選擇地重新渲染只改變了內容的AuthorList的孩子,這正是我想要做的。 – deadcode