state
或新的props
,它会重新呈现自己及其所有子项。这通常没问题。但是React提供了一个生命周期方法,您可以在子组件接收新state
或props
时调用它,并特别声明组件是否应该更新。方法是shouldComponentUpdate()
,它将nextProps
和nextState
作为参数。此方法是优化性能的有用方法。例如,默认行为是您的组件在收到新props
时重新渲染,即使props
未更改。您可以使用shouldComponentUpdate()
通过比较props
来防止这种情况。该方法必须返回一个boolean
值,告诉React是否更新组件。您可以将当前道具( this.props
)与下一个道具( nextProps
)进行比较,以确定是否需要更新,并相应地返回true
或false
。 shouldComponentUpdate()
方法添加到名为OnlyEvens
的组件中。目前,此方法返回true
因此每次收到新props
时, OnlyEvens
重新渲染。修改方法,以便OnlyEvens
更新仅当value
的新道具的是偶数。单击“ Add
按钮,在触发其他生命周期挂钩时,在浏览器控制台中查看事件的顺序。 Controller
组件应将OnlyEvens
组件呈现为OnlyEvens
组件。
testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find("Controller").length === 1 && mockedComponent.find("OnlyEvens").length === 1; })(), "The Controller
component should render the OnlyEvens
component as a child.");'
- text: 应该在OnlyEvens
组件上定义shouldComponentUpdate
方法。
testString: 'assert((() => { const child = React.createElement(OnlyEvens).type.prototype.shouldComponentUpdate.toString().replace(/s/g,""); return child !== "undefined"; })(), "The shouldComponentUpdate
method should be defined on the OnlyEvens
component.");'
- text: OnlyEvens
组件应返回一个h1
标记,该标记呈现this.props.value
的值。
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 1000 }); return waitForIt(() => mockedComponent.find("h1").html()); }; const second = () => { mockedComponent.setState({ value: 10 }); return waitForIt(() => mockedComponent.find("h1").html()); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === "OnlyEvens
component should return an h1
tag which renders the value of this.props.value
."); }; '
- text: OnlyEvens
只有在nextProps.value
为偶数OnlyEvens
应该重新渲染。
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 8 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const second = () => { mockedComponent.setState({ value: 7 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const third = () => { mockedComponent.setState({ value: 42 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(firstValue === "8" && secondValue === "8" && thirdValue === "42", "OnlyEvens
should re-render only when nextProps.value
is even."); }; '
```