【发布时间】:2017-04-05 13:55:45
【问题描述】:
编辑:我重写了这个问题以澄清我所追求的 - 感谢到目前为止帮助我磨练它的人。
我试图了解如何最好地在 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,但我不希望为所有内容未更改的Author 和Publication 对象调用render() .
从这个答案:
ReactJS - Does render get called any time "setState" is called?
React 组件的 render() 函数将在其状态或其任何父级的状态发生变化时被调用 - 无论该状态变化是否与该组件的道具有关。可以使用 shouldComponentUpdate 更改此行为。
人们如何处理像上面这样的复杂状态 - 在每次状态更改时对大量组件调用 render() 似乎不是一个好的解决方案(即使生成的渲染对象相同,因此不会发生更改到实际的 DOM)。
【问题讨论】:
标签: reactjs