美好的一天!
当您创建布局组件时遇到以下问题 - 如果组件布局接受子组件作为子组件,并且每当当前和新的props.children彼此不相等时调用shouldComponentUpdate方法(即使实际上这些子组件也是如此)是一样的。)
这里的部分代码:
class Layout extends React.Component {
shouldComponentUpdate(newProps) {
console.log(
`%c COL SHOULD RENDER ${newProps.children === this.props.children}`,
"color: green;"
);
return true;
}
render() {
console.log('render');
return (
<div className="Layout">
{this.props.children}
</div>
);
}
}
const Input = props =>
<div>
{props.value}
</div>;
const Page = () =>
<Layout>
<Input value="foo" />
<Input value="bar" />
</Layout>;
class App extends React.Component {
constructor() {
super();
this.state = {
styles: {
fontFamily: "sans-serif",
textAlign: "center",
color: "black"
}
};
this.changeStylesColor = this.changeStylesColor.bind(this);
}
changeStylesColor() {
this.setState({
styles: {
fontFamily: "sans-serif",
textAlign: "center",
color: "red"
}
});
}
render() {
return (
<div style={this.state.styles}>
<h2>
Start editing to see some magic happen {"\u2728"}
</h2>
<Page />
<button onClick={this.changeStylesColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
当您点击按钮&#34;更改颜色&#34;我们正在更改主App组件的状态,它会重新绘制Layout组件,其子组件没有更改。
出于某种原因,除了实现你的shouldComponentUpdate(在大量传入属性时没用),孩子们并不总是彼此相等,除了如何避免这些简单的静态组件重绘?