1. setState
1.1 setState 的两种写法
1.2 对象式
let { count } = this.state
this.setState({
count: count + 1
}, () => {
console.log(count)
})
console.log(count)
1.3 函数式
this.setState((state, props) => {
return {
count: state.count + 1
}
},[callback])
2. lazyLoad(路由懒加载)
import React, { Component, lazy, Suspense } from "react";
import { Route, NavLink } from "react-router-dom";
let About = lazy(() => import("./components/About/About"));
let Home = lazy(() => import("./components/Home/Home"));
export default class App extends Component {
render() {
return (
<div className="App">
<div>
<NavLink to="/demo/about" children="About" />
<NavLink to="/demo/home" children="Home" />
</div>
<div className="content">
<Suspense fallback={<h1>loading...</h1>}>
<Route path="/demo/about" component={About} />
<Route path="/demo/home" component={Home} />
</Suspense>
</div>
</div>
);
}
}
3. hooks
3.1 State Hook
import React, { useState } from "react";
export default function App() {
let [count, setCount] = React.useState(0);
let [arr, setArr] = useState([{name: "小红", age: 18}]);
function add() {
setCount(count + 1);
}
function addInfo() {
setArr([...arr, {name: "小黄", age: 19}])
}
return (
<div>
<h1>{count}</h1>
<button onClick={add}>点我加1</button>
<button onClick={addInfo}>点我加添加信息</button>
</div>
);
}
3.2 Effect Hook
import { useEffect } from "react"
export default function App() {
let [count, setCount] = React.useState(0);
useEffect(() => {
return () => {
}
},[])
function add() {
setCount(count + 1);
}
return (
<div>
<h1>{count}</h1>
<button onClick={add}>点我加1</button>
</div>
);
}
3.3 Ref Hook
import { useRef } from "react"
4. Fragment(虚拟DOM)
import { Fragment } from "react"
...render(){
return <Fragment></Fragment>
}
5. Context(祖孙传值)
import { createContext, useContext } from "react";
const MyContext = createContext();
const { Provider, Consumer } = MyContext;
function App() {
return (
<div>
<Provider value="要传入的数据">
</Provider>
</div>
)
}
function Demo1(){
return (
<div>
<Consumer>
{(value) => {
}}
</Consumer>
</div>
)
}
function Demo2() {
const value = useContext(MyContext)
return <div></div>
}
6. 组件优化
6.1 Component 的2个问题
- 只要执行了 setState(),即使不改变状态数据,组件也会重新 render
- 只要当前组件重新 render,子组件也会重新 render
6.2 解决方案
只有当前组件的 state 或 props 修改时,才会 render
- 设置 shouldComponentUpdate 声明周期方法
shouldComponentUpdate(nextState, nextProps) {
}
- 使用 PureComponent
import { PureComponent } from "react"
class App extends PureComponent {
}
7. Render Props(逆向传值)
function App() {
return (
<div>
<p> 我是App组件</p>
<Child render={(value) => <span>{`name:${value.name},age:${value.age}`}</span>} />
</div>
);
}
function Child(props) {
return (
<div>
<p> 我是Child组件</p>
{props.render({ name: "小红", age: 18 })}
</div>
);
}
8. 错误边界
class App extends Component {
static getDerivedStateFromError() {
return {
hasError: true
}
}
componentDidCatch() {
console.log("打印错误信息")
}
}
9. 组件通信
- 父子:props、renderProps(逆向传递)
- 兄弟:redux(集中式管理)、发布订阅
- 祖孙:redux(集中式管理)、context、发布订阅
|