react初学05(函数组件)

235 阅读1分钟

创建方式

函数创建

const Hello = (props)={
reruen <div>{props.message}</div>
}
const Hello = props =><div>{props.message}</div>

function Hello(props){
return <div>{props.message}
}

函数组件替代class组件

面临的两个问题

  • 函数组件没有state
  • 函数组件没有生命周期

没有state

  • Reactv16.8.0推出Hooks API
  • 其中useState可以解决问题

没有生命周期

  • useEffect可以解决问题

useEffect

模拟componentDidMount

useEffect(()=>{console.log("第一次渲染")},[])

模拟componentDidUpdate

useEffect(()=>{console.log("任意属性变更了")}) useEffect(()=>{console.log("n变了")},[n])

模拟componentWillUnmount

useEffect(()=>{
console.log('第一次渲染')
return ()=>{
console.log('组件要消失了')}
})

constructctor

  • 函数组件执行的时候,就相当于constructor

shouldComponentUpdate

  • 使用React.memo和useMemo可以解决

render

  • 函数组件的返回值就是render的返回值