React 16.8+ 新特性

1,269 阅读2分钟

一、定时器的使用


//定时器的使用
 componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }
 
//不重新渲染组件
 this.state.comment = 'Hello';
  
// 修改状态值: 使用state值计算而得时
 this.setState((prevState, props) => ({
   counter: prevState.counter + props.increment
 }));
 

二、组件与纯组件


// Component 组件
class Child extends Component {
    constructor(props){
        super(props);
    }
    render(){
        return <div>hello world</div>;
    }
}

// PureComponent 纯组件, state不改变不重新渲染
class Child extends PureComponent {
    constructor(props){
        super(props);
    }
    render(){
        return <div>hello world</div>;
    }
}

// 函数组件, moment可以包装成纯组件
const Child = memo(() => {
    return <div>hello world</div>;
});

三、高阶组件


// 高阶组件: 把组件作为参数传递, 返回一个新组件
const Hoc = Comp => {
    class WrapComp extends Component {
        state = {
            info: "hello world"
        };
        render() {
            return <Comp info={this.state.info} />;
        }
    }
    return WrapComp;
};
const WrapFC = () => {
    return <div>welcome</div>;
};
const Welcom = Hoc(WrapFC);

四、组件插槽


// 组件插槽, 类似reactDOM的render方法, 把Comp挂在到element上
React.createPortal(Comp, Element)

五、context


// context: 传递 props
const Context = React.createContext({a: "hello world"}); // 初始值
const {Provider, Consumer} = Context;

<Provider value={{a: "hello world"}}>
    <Parent></Parent>
</Provider>

<Child>
    <Consumer>{value => {
        // 这里的value为 {a: "hello world"}
    }}</Consumer>
</Child>

// 获取全局的状态
class MyClass extends React.Component {
    render() {
      let value = this.context;
      /* 基于 MyContext 组件的值进行渲染 */
    }
}
MyClass.contextType = MyContext;

class MyClass extends React.Component { // 
    static contextType = MyContext;
    render() {
      let value = this.context;
      /* 基于这个值进行渲染工作 */
    }
}

六、懒加载、动态加载


// 动态加载组件: Suspense Lazy (新的)  react-loadable import (旧的)
const LazyComp = Lazy(()=> import("./comp")); // 必须用Suspense包裹

<Suspense fallback={()=> (
    <div style={{ height: "100vh" }}>
        <Loading />
    </div>
)}>
    <LazyComp></LazyComp>
</Suspense>

七、错误边界渲染


// 错误边界渲染
class ErrorBoundary extends React.Component {
    static getDerivedStateFromError(error) {
        // 更新 state 使下一次渲染能够显示降级后的 UI
        return { hasError: true,error };
    }

    constructor(props) {
        super(props);
        this.state = {
            hasError: false,
            error: null
        };
    }

    componentDidCatch(error, errorInfo) {
        // TODO: 这里进行错误处理
    }

    render() {
        if (this.state.hasError) {
            return this.props.fallback;;
        }
        return this.props.children;
    }
}

const App = () => {
    return (
        <ErrorBoundary fallback={<h2>Could not fetch posts.</h2>}>
            {/* 里面的代码抛错, throw new Error() */}
        </ErrorBoundary>
    );
};