样式化的组件会导致不需要的重新渲染
Styled component causes unwanted rerender
我有一个看起来像这样的应用程序
class App extends Component {
state = {
config: {}
};
submitForm(formData) {
this.setState({
config: newConfig(formData)
});
}
render() {
return (
<div className="App">
<Form submit={formData => this.submitForm(formData)} />
<Body config={this.state.config} />
</div>
);
}
}
function Form(props) {
const QueryBox = styled.div`
background-color: #1080f2;
padding: 1em;
`;
return (
<QueryBox>
<MyForm submit={props.submit} />
</QueryBox>
);
}
class MyForm extends React.Component {
...
}
现在我的问题是样式化的 div 导致 MyForm 组件在 App
组件的 每个 状态更改时重新呈现。
这是为什么呢。这是预期的行为吗(这会使样式化的组件对我不可用)。有没有办法改变它?
您的 QueryBox
将成为 Form
每次渲染的全新组件。将它移到 Form
之外,它将按预期工作。
const QueryBox = styled.div`
background-color: #1080f2;
padding: 1em;
`;
function Form(props) {
return (
<QueryBox>
<MyForm submit={props.submit} />
</QueryBox>
);
}
我有一个看起来像这样的应用程序
class App extends Component {
state = {
config: {}
};
submitForm(formData) {
this.setState({
config: newConfig(formData)
});
}
render() {
return (
<div className="App">
<Form submit={formData => this.submitForm(formData)} />
<Body config={this.state.config} />
</div>
);
}
}
function Form(props) {
const QueryBox = styled.div`
background-color: #1080f2;
padding: 1em;
`;
return (
<QueryBox>
<MyForm submit={props.submit} />
</QueryBox>
);
}
class MyForm extends React.Component {
...
}
现在我的问题是样式化的 div 导致 MyForm 组件在 App
组件的 每个 状态更改时重新呈现。
这是为什么呢。这是预期的行为吗(这会使样式化的组件对我不可用)。有没有办法改变它?
您的 QueryBox
将成为 Form
每次渲染的全新组件。将它移到 Form
之外,它将按预期工作。
const QueryBox = styled.div`
background-color: #1080f2;
padding: 1em;
`;
function Form(props) {
return (
<QueryBox>
<MyForm submit={props.submit} />
</QueryBox>
);
}