我有一个 React 的父组件和子组件。在这里,我将 id 作为 Prop 从 parent 传递给 child ,我正在保存使用状态输入的文本区域的值。每当我在文本区域中输入时。子组件得到更新。如何防止子组件更新文本区域中输入的每个值?请帮助我。
class Child extends React.Component {
constructor() {
super();
}
componentWillMount(){
console.log('child component Will '+this.props.id);
}
componentDidMount(){
console.log('child component Did '+this.props.id);
}
render() {
console.log('child render '+this.props.id);
return <p>Child {this.props.id}</p>;
}
}
class Application extends React.Component {
constructor(){
super();
this.state={
id:1,
textValue:undefined
}
}
componentWillMount(){
console.log('parent component Will');
}
componentDidMount(){
console.log('parent component Did');
}
render() {
console.log('parent render');
return <div>
<textarea onChange={(event)=>{
this.setState(
{textValue:(event.target.value)})
}
}></textarea>
<Child id='1'/>
<Child id='2'/>
</div>;
}
}
ReactDOM.render(<Application />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.js"></script>
<div id="app"></div>
最佳答案
您可以使用 React.PureComponent
而不是扩展 React.Component
。两者之间的区别在于,后者还对每个渲染之间的 props
和 state
进行了浅比较;如果什么都没有改变,它就不会更新。
official documentation上也推荐这个:
If your React component's
render()
function renders the same result given the same props and state, you can useReact.PureComponent
for a performance boost in some cases.
看看下面的代码。我只更改了第一行代码以扩展正确的类。
class Child extends React.PureComponent {
constructor() {
super();
}
componentWillMount(){
console.log('child component Will '+this.props.id);
}
componentDidMount(){
console.log('child component Did '+this.props.id);
}
render() {
console.log('child render '+this.props.id);
return <p>Child {this.props.id}</p>;
}
}
class Application extends React.Component {
constructor(){
super();
this.state={
id:1,
textValue:undefined
}
}
componentWillMount(){
console.log('parent component Will');
}
componentDidMount(){
console.log('parent component Did');
}
render() {
console.log('parent render');
return <div>
<textarea onChange={(event)=>{
this.setState(
{textValue:(event.target.value)})
}
}></textarea>
<Child id='1'/>
<Child id='2'/>
</div>;
}
}
ReactDOM.render(<Application />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.js"></script>
<div id="app"></div>
编辑:我更新了您的问题并使您的代码可以在代码片段中运行,以便它可以与我的片段进行比较。
关于javascript - 防止在 react 中更改状态时呈现子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45800175/