MST

星途 面试题库

面试题:React中State和Props的复杂应用区别

假设你正在开发一个多层嵌套的React应用,子组件需要根据父组件传递的Props来更新自身的显示状态。但在某些情况下,子组件也需要有自己独立变化的状态。请描述如何合理地使用State和Props来实现这一需求,同时避免不必要的重新渲染。
12.2万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试
  1. 使用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;
    
  2. 子组件自身状态管理
    • 在子组件中,定义自己独立变化的状态。例如:
    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;
    
  3. 避免不必要的重新渲染
    • 使用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;