如何避免额外渲染与 redux 反应
How to avoid extra rendering in react with redux
我有下一个对象:
Book = {
id: 1,
titel: "Some Book",
sections: [
{id: 1,
titel: "Section Titel",
pages: [
{id: 1, content: "Some text"},
{id: 2, content: "Some text"},
{id: 3, content: "Some text"}
]
},
{id: 2,
titel: "Section Titel",
pages: [
{id: 1, content: "Some text"},
{id: 2, content: "Some text"}
]
}
]
}
Book
对象存储在 Redux 存储中 (state.Book
)。
我有可视化此 Book
对象的组件。
组件 Book
渲染一个或多个 Section
组件,每个 Section
组件渲染 Page
组件。
Book
通过 connect
函数从 react-redux 订阅了 Redux 并监听了 store.Book
, hole object.
很明显,当 Book
的 titel
发生变化时,洞 Book
对象将被重新渲染,包括所有 Sections
和 Pages
.
有两个问题:
如果只更改 Book.titel
,React 引擎真的会重新渲染 Sections
和 Pages
吗?或者它会识别组件的其他部分没有改变,不会重新渲染它们。
如果它会重新渲染,那么最好的避免方法是什么?我是否也应该将 Section
和 Page
组件订阅到 Store
?但这并不能解决问题,因为Book
监听的是空洞state.Book
对象。或者我应该只订阅 Book
组件到 state.Book.id
和 state.Book.titel
,然后在内部使用 this.context.store
将数据传递到内部组件?
提前致谢。
- 是的,React 会在
Sections
和 Pages
中调用 render
方法,但不要担心性能问题,因为这些操作成本非常低。 Virtual DOM 将抽象所有繁重的操作(即操纵 DOM),最大限度地减少对性能的影响。您可以自己 运行 进行一些快速测试,以了解用户体验如何完全不受更改此大小的影响。
- 我不建议阻止重新渲染(正如我在 #1 中所说的那样,这是一项不昂贵的操作),但如果您真的想要,可以在
Section
组件中使用 shouldComponentUpdate
。每当您觉得 Section
或其子组件不需要渲染时,您只需要 return false
我有下一个对象:
Book = {
id: 1,
titel: "Some Book",
sections: [
{id: 1,
titel: "Section Titel",
pages: [
{id: 1, content: "Some text"},
{id: 2, content: "Some text"},
{id: 3, content: "Some text"}
]
},
{id: 2,
titel: "Section Titel",
pages: [
{id: 1, content: "Some text"},
{id: 2, content: "Some text"}
]
}
]
}
Book
对象存储在 Redux 存储中 (state.Book
)。
我有可视化此 Book
对象的组件。
组件 Book
渲染一个或多个 Section
组件,每个 Section
组件渲染 Page
组件。
Book
通过 connect
函数从 react-redux 订阅了 Redux 并监听了 store.Book
, hole object.
很明显,当 Book
的 titel
发生变化时,洞 Book
对象将被重新渲染,包括所有 Sections
和 Pages
.
有两个问题:
如果只更改
Book.titel
,React 引擎真的会重新渲染Sections
和Pages
吗?或者它会识别组件的其他部分没有改变,不会重新渲染它们。如果它会重新渲染,那么最好的避免方法是什么?我是否也应该将
Section
和Page
组件订阅到Store
?但这并不能解决问题,因为Book
监听的是空洞state.Book
对象。或者我应该只订阅Book
组件到state.Book.id
和state.Book.titel
,然后在内部使用this.context.store
将数据传递到内部组件?
提前致谢。
- 是的,React 会在
Sections
和Pages
中调用render
方法,但不要担心性能问题,因为这些操作成本非常低。 Virtual DOM 将抽象所有繁重的操作(即操纵 DOM),最大限度地减少对性能的影响。您可以自己 运行 进行一些快速测试,以了解用户体验如何完全不受更改此大小的影响。 - 我不建议阻止重新渲染(正如我在 #1 中所说的那样,这是一项不昂贵的操作),但如果您真的想要,可以在
Section
组件中使用shouldComponentUpdate
。每当您觉得Section
或其子组件不需要渲染时,您只需要 returnfalse