文档详情

一文带你了解React中的函数组件.docx

发布:2025-05-22约3.96千字共7页下载文档
文本预览下载声明

一文带你了解React中的函数组件

目录1.创建方式2.函数组件代替类组件3.自定义Hook之useUpdate补充:函数组件代替class组件总结

1.创建方式

//写法一

constHello=(props)={

returndiv{props.message}/div

//写法二

constHello=props=div{props.message}/div

//写法三

functionHello(props){

returndiv{props.message}/div

}

2.函数组件代替类组件

面临的问题

函数组件没有state=Reactv16.8.0推出HooksAPI,其中的一个API叫做useState可以解决问题函数组件没有生命周期=Reactv16.8.0推出HooksAPI,其中的一个API叫做useEffect可以解决问题

我们对比一下两种组件实现n+1的例子

类组件

classAppextendsReact.Component{

constructor(props){

super(props);

this.state={

n:0

addNum=()={

this.setState({n:this.state.n+1})

render(){

return(

divclassName=App

spann:{this.state.n}/span

buttonthis.addNum}n+1/button

/div

函数组件

constApp=props={

const[n,setN]=React.useState(0)

functionaddNum(){

setN(n+1)

return(

divclassName=App

buttonaddNum}+1/button

/div

相比之下函数组件更为简洁一些

使用useEffect解决生命周期问题

1.模拟componentDidMount首次渲染

useEffect(()={//模拟componentDidMount首次渲染

console.log(useeffect)

},[])//空数组必须写

2.模拟componentDidUpdate

const[n,setN]=React.useState(0)

useEffect(()={//模拟componentDidUpdate

console.log(n变化了)

},[n])//数组里面可以写多个参数表示监听多个变量

useEffect(()={//模拟componentDidUpdate

console.log(任意属性变更了)

})//不写数组表示监听所有useState的变量

//但是这样在第一次渲染时也会触发函数的执行

解决方法使用自定义Hook见下一标题

3.模拟componentWillUnmount

useEffect(()={

return()={

console.log(Child销毁了)

})//返回一个函数在销毁时执行

4.constructor

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

5.shouldComponentUpdate

后面的React.memo和useMemo可以解决

6.render

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

//模拟render里面写逻辑

constX=(props)={

console.log(我是要写的逻辑)

return(

div逻辑模拟/div

constApp=props={

let[childVisible,setChildVisible]=useState(true)

constchangeVisible=()={

setChildVisible(!childVisible)

return(

divclassName=App

{childVisiblebuttonchangeVisible

显示全部
相似文档