函数式组件和类组件:

各有千秋,之前一直习惯用类组件,但是官方最新的一直推函数式并且声明了不废除类组件,所以可以同时使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const Tup = (props:any) => {
const [test, setTest] = useState('111')
return (
<div onClick={()=>{
setTest('222')
}}>{
test
}</div>
)
}
export default Tup;


export default class Tup extends React.Component {

constructor(props: any){
super(props)
this.state = {
test: '111'
}
}
render(){
return (
<div onClick={()=>{
this.setState({
test: 222
})
}}>{
this.state.test
}</div>
)
}
}

通过react-router-cache-route实现缓存

1
2
3
4
5
6
7
8
9
10
//router.js
import {CacheRoute,CacheSwitch} from 'react-router-cache-route'

<CacheSwitch>
<CacheRoute exact path="/home" component={Home} />
{/* 404 */}
<Route path='/404' component={NotFoundPage} />
{/* 其他重定向到 404 */}
<Redirect from='*' to='/404' />
</CacheSwitch>

React Hook中useEffect代替的生命周期

1
2
3
4
5
6
7
function Example() {
// 当我们指定第二个参数为空数组就可以代替我们类组件中的componentDidMount
useEffect(() => {
console.log('Did mount!');
}, []);
return <div></div>;
}
1
2
3
4
5
6
7
function Example() {
// 当我们第二个参数监听一个状态的时候代替componentDidUpdate
useEffect(() => {
console.log('Did update!');
},[a]);
return <div></div>;
}
1
2
3
4
5
6
7
8
9
function Example() {
// 当我们不指定第二个参数的同时并在第一个参数中返回一个函数就可以代替我们类组件中的componentWillUnmount
useEffect(() => {
return () => {
console.log('will unmount');
}
});
return <div></div>;
}