React 函数组件
创建函数组件方式
const Hello = (props) => {
return <div>{props.message}</div>
}
// 缩写
const Hello = props => <div>{props.message}</div>
//另一种方式
function Hello (props){
return <div>{props.message}</div>
}
函数组件替代class组件
有两个问题
- 函数组件没有state
- 函数组件没有生命周期
没有 State
- React v16.8.0 推出 Hooks API
- 其中一个API 叫做 useState可以解决问题
import React, { useState } from 'react';
function Example() {
// 声明一个叫 "count" 的 state 变量
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
// 等价于class
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
没有生命周期
- Hooks API 的 useEffect 可以解决这个问题
useEffect
模拟componentDidMount
- useEffect(()=>{ console.log(‘第一次渲染’) }, [] )
模拟componentDidUpdate
- useEffect(()=>{ console.log(‘任意属性变更’)})
- useEffect(()=>{ console.log(‘n 变了’)}, [n])
模拟componentWillmount
useEffect(()=>{
console.log('第一次渲染')
return ()=>{
console.log('组件要死了')
}
})
其他生命周期怎么模拟
constructor
- 函数组件执行的时候,就相当于constructor
shouldComponentUpdate
- 可以使用React.memo 和 useMemo替代
render
- 函数组件的返回值就是render的返回值
总结
- 函数组件更为简单,能用函数组件就用函数组件。
自定义Hook 之useUpdate
自定义组件必须是use开头的
import React,{useState,useEffect} from "react"
const useUpdate => (fn,dep) => {
const [count,setCount] = useState(0)
usrEffect(()={
setCount(x => x+1)
},[dep])
useEffect(()={
if(count > 1){
fn()
}
},[count,fn])
}
const App = props ={
const [n,setN] = useStaet(0)
const onclick = ()=>{
setN(n + 1)
}
}
useUpdate(()={
console.log('n变了')
},n)
return (
<div>
{n}
<button onClick={onClick}>+1</button>
</div>
)
export default App;
useUpdate
- 第一次由undefined 变成0时不执行函数
- 第二次变化时,执行函数
- 第三次变化时,执行函数...
这就是自定义Hook。