面试题答案
一键面试- 使用Props传递数据:
- 在父组件中,将子组件需要依赖的数据作为Props传递给子组件。例如:
import React from'react'; import ChildComponent from './ChildComponent'; class ParentComponent extends React.Component { constructor(props) { super(props); this.state = { dataForChild: 'initial data' }; } render() { return ( <div> <ChildComponent data={this.state.dataForChild} /> </div> ); } } export default ParentComponent;
- 子组件自身状态管理:
- 在子组件中,定义自己独立变化的状态。例如:
import React from'react'; class ChildComponent extends React.Component { constructor(props) { super(props); this.state = { localState: 'initial local state' }; } render() { return ( <div> <p>{this.props.data}</p> <p>{this.state.localState}</p> </div> ); } } export default ChildComponent;
- 避免不必要的重新渲染:
- 使用React.memo:对于函数式子组件,可以使用
React.memo
来包裹组件。它会对Props进行浅比较,如果Props没有变化,组件不会重新渲染。例如:
import React from'react'; const ChildComponent = React.memo((props) => { return ( <div> <p>{props.data}</p> </div> ); }); export default ChildComponent;
- shouldComponentUpdate:对于类组件,可以在子组件中重写
shouldComponentUpdate
方法。在这个方法中,手动比较当前Props和下一个Props,以及当前State和下一个State,只有在必要时才返回true
进行重新渲染。例如:
import React from'react'; class ChildComponent extends React.Component { shouldComponentUpdate(nextProps, nextState) { // 比较props和state,只有在需要时返回true if (nextProps.data!== this.props.data || nextState.localState!== this.state.localState) { return true; } return false; } constructor(props) { super(props); this.state = { localState: 'initial local state' }; } render() { return ( <div> <p>{this.props.data}</p> <p>{this.state.localState}</p> </div> ); } } export default ChildComponent;
- 使用React.memo:对于函数式子组件,可以使用