React中第一个组件状态变更时,如何阻止第二个组件重渲染?
嘿,我帮你把这个React状态提升的POC代码整理成规范的Markdown格式了,还补充了必要的代码补全和说明,方便你查看和复用:
React状态提升POC:Main组件统一管理状态并传递给子组件
这是一个典型的React状态提升实践示例,应用的所有状态由Main组件集中维护,当状态发生变更时,新状态会通过props传递给子组件Comp1和Comp2,从而触发子组件的重新渲染。
import * as React from 'react' import * as ReactDOM from 'react-dom' // 定义Comp1的props类型 interface IProps1 { inputValue: string; onInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void; } class Comp1 extends React.Component<IProps1, any> { render() { console.log('going to render Component1') return ( <React.Fragment> <input type='text' value={this.props.inputValue} onChange={this.props.onInputChange} placeholder="输入内容触发状态更新" /> </React.Fragment> ) } } // 定义Comp2的props类型 interface IProps2 { displayText: string; } class Comp2 extends React.Component<IProps2, any> { render() { console.log('going to render Component2') return ( <div> <p>当前输入的内容是:{this.props.displayText}</p> </div> ) } } // Main组件,维护全局状态 class Main extends React.Component<any, { inputValue: string }> { constructor(props: any) { super(props); // 初始化状态 this.state = { inputValue: '' }; } handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { // 更新Main组件的状态 this.setState({ inputValue: e.target.value }); } render() { return ( <div> <h2>React状态提升演示</h2> {/* 将状态和回调作为props传递给Comp1 */} <Comp1 inputValue={this.state.inputValue} onInputChange={this.handleInputChange} /> {/* 将状态作为props传递给Comp2 */} <Comp2 displayText={this.state.inputValue} /> </div> ) } } // 渲染Main组件到DOM ReactDOM.render(<Main />, document.getElementById('root'));
核心要点
- 状态集中管理:所有共享状态由
Main组件统一持有,避免了子组件之间的状态同步问题 - props传递状态:子组件通过props接收状态和回调函数,实现了React的单向数据流
- 自动重渲染:当
Main组件的状态更新时,依赖该状态的子组件会自动重新渲染,你可以通过控制台的console.log输出看到渲染触发的日志
内容的提问来源于stack exchange,提问作者Knows Not Much
相关产品推荐
相关产品推荐

