一、定时器的使用
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
this.state.comment = 'Hello';
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
二、组件与纯组件
class Child extends Component {
constructor(props){
super(props);
}
render(){
return <div>hello world</div>;
}
}
class Child extends PureComponent {
constructor(props){
super(props);
}
render(){
return <div>hello world</div>;
}
}
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);
四、组件插槽
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) {
return { hasError: true,error };
}
constructor(props) {
super(props);
this.state = {
hasError: false,
error: null
};
}
componentDidCatch(error, errorInfo) {
}
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>
);
};