您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

react hook和class的区别有哪些

2024/4/20 7:30:08发布6次查看
区别:1、hooks的写法比class简洁;2、hooks的业务代码比class更加聚合;3、class组件的逻辑复用通常用render props以及hoc两种方式,而react hooks提供了自定义hooks来复用逻辑。
本教程操作环境:windows7系统、react17.0.1版、dell g3电脑。
react hooks与class组件有哪些区别?下面就来带大家对比一下react hooks和class组件,聊聊它们的区别。
react-hooks解决的问题函数组件中不能拥有自己的状态(state)。在hooks之前函数组件是无状态的,都是通过props来获取父组件的状态,但是hooks提供了usestate来维护函数组件内部的状态。
函数组件中不能监听组件的生命周期。useeffect聚合了多个生命周期函数。
class组件中生命周期较为复杂(在15版本到16版本的变化大)。
class组件逻辑难以复用(hoc,render props)。
hooks对比class的好处(对比)1、写法更加的简洁我们以最简单的计数器为例:
class组件
class exampleofclass extends component {  constructor(props) {    super(props)    this.state = {      count: 1    }  }  handleclick = () => {    let { count } = this.state    this.setstate({      count: count+1    })  }  render() {    const { count } = this.state    return (      dc6dce4a544fdca2df29d5ac0ea9906b        e388a4556c0f65e1904146cc1a846beeyou click { count }94b3e26ee717c64999d7867364b1b4a3        58d87a863b0fd08858af212a24752208点击65281c5ac262bf6d81768915a4a77ac0      16b28748ea4df4d9c2150843fecfba68    )  }}
hooks
function exampleofhooks() { const [count, setcount] = usestate(0) const handleclick = () => { setcount(count + 1) } return ( <div> <p>you click { count }</p> <button onclick={handleclick}>点击</button> </div> )}
可以看到使用hooks的代码相比class组件代码更加的简洁、清晰。
2、业务代码更加聚合使用class组件经常会出现一个功能出现在两个生命周期函数内的情况,这样分开写有时候可能会忘记。比如:
let timer = nullcomponentdidmount() { timer = setinterval(() => { // ... }, 1000)}// ...componentwillunmount() { if (timer) clearinterval(timer)}
由于添加定时器和清除定时器是在两个不同的生命周期函数,中间可能会有很多其他的业务代码,所以可能会忘记清除定时器,如果在组件卸载时没有添加清楚定时器的函数就可能会造成内存泄漏、网络一直请求等问题。
但是使用hooks可以让代码更加的集中,方便我们管理,也不容易忘记:
useeffect(() => { let timer = setinterval(() => { // ... }, 1000) return () => { if (timer) clearinterval(timer) }}, [//...])
3、逻辑复用方便class组件的逻辑复用通常用render props以及hoc两种方式。react hooks提供了自定义hooks来复用逻辑。
下面以获取鼠标在页面的位置的逻辑复用为例:
class组件render props方式复用
import react, { component } from 'react'class mouseposition extends component { constructor(props) { super(props) this.state = { x: 0, y: 0 } } handlemousemove = (e) => { const { clientx, clienty } = e this.setstate({ x: clientx, y: clienty }) } componentdidmount() { document.addeventlistener('mousemove', this.handlemousemove) } componentwillunmount() { document.removeeventlistener('mousemove', this.handlemousemove) } render() { const { children } = this.props const { x, y } = this.state return( <div> { children({x, y}) } </div> ) }}// 使用class index extends component { constructor(props) { super(props) } render() { return ( <mouseposition> { ({x, y}) => { return ( <div> <p>x:{x}, y: {y}</p> </div> ) } } </mouseposition> ) }}export default index
自定义hooks方式复用
import react, { useeffect, usestate } from 'react'function useposition() { const [x, setx] = usestate(0) const [y, sety] = usestate(0) const handlemousemove = (e) => { const { clientx, clienty } = e setx(clientx) sety(clienty) } useeffect(() => { document.addeventlistener('mousemove', handlemousemove) return () => { document.removeeventlistener('mousemove', handlemousemove) } }) return [ {x, y} ]}// 使用function index() { const [position] = useposition() return( <div> <p>x:{position.x},y:{position.y}</p> </div> )}export default index
可以很明显的看出使用hooks对逻辑复用更加的方便,使用的时候逻辑也更加清晰。
hooks常见的一些api使用1、usestate语法
const [value, setvalue] = usestate(0)
这种语法方式是es6的数组结构,数组的第一个值是声明的状态,第二个值是状态的改变函数。
每一帧都有独立的状态
个人理解针对每一帧独立的状态是采用了闭包的方法来实现的。
function example() { const [val, setval] = usestate(0) const timeoutfn = () => { settimeout(() => { // 取得的值是点击按钮的状态,不是最新的状态 console.log(val) }, 1000) } return ( <> <p>{val}</p> <button onclick={()=>setval(val+1)}>+</button> <button onclick={timeoutfn}>alertnumber</button> </> )}
当组件的状态或者props更新时,该函数组件会被重新调用渲染,并且每一次的渲染都是独立的都有自己独立的props以及state,不会影响其他的渲染。
2、useeffect语法
useeffect(() => { //handler function... return () => { // clean side effect }}, [//dep...])
useeffect接收一个回调函数以及依赖项,当依赖项发生变化时才会执行里面的回调函数。useeffect类似于class组件didmount、didupdate、willunmount的生命周期函数。
注意点
useeffect是异步的在组件渲染完成后才会执行
useeffect的回调函数只能返回一个清除副作用的处理函数或者不返回
如果useeffect传入的依赖项是空数组那么useeffect内部的函数只会执行一次
3、usememo、usecallbackusememo和usecallback主要用于减少组件的更新次数、优化组件性能的。
usememo接收一个回调函数以及依赖项,只有依赖项变化时才会重新执行回调函数。
usecallback接收一个回调函数以及依赖项,并且返回该回调函数的memorize版本,只有在依赖项重新变化时才会重新新的memorize版本。
语法
const memodate = usememo(() => data, [//dep...])const memocb = usecallback(() => {//...}, [//dep...])
在优化组件性能时针对class组件我们一般使用react.purecomponent,purecomponent会在shouldupdate进行一次钱比较,判断是否需要更新;针对函数组件我们一般使用react.memo。但是在使用react hooks时由于每一次渲染更新都是独立的(生成了新的状态),即使使用了react.memo,也还是会重新渲染。
比如下面这种场景,改变子组件的name值后由于父组件更新后每次都会生成新值(addage函数会改变),所以子组件也会重新渲染。
function parent() { const [name, setname] = usestate('cc') const [age, setage] = usestate(22) const addage = () => { setage(age + 1) } return ( <> <p>父组件</p> <input value={name} onchange={(e) => setname(e.target.value)} /> <p>age: {age}</p> <p>-------------------------</p> <child addage={addage} /> </> )}const child = memo((props) => { const { addage } = props console.log('child component update') return ( <> <p>子组件</p> <button onclick={addage}>click</button> </> )})
使用usecallback优化
function parent() { const [name, setname] = usestate('cc') const [age, setage] = usestate(22) const addage = usecallback(() => { setage(age + 1) }, [age]) return ( <> <p>父组件</p> <input value={name} onchange={(e) => setname(e.target.value)} /> <p>age: {age}</p> <p>-------------------------</p> <child addage={addage} /> </> )}const child = memo((props) => { const { addage } = props console.log('child component update') return ( <> <p>子组件</p> <button onclick={addage}>click</button> </> )})
只有usecallback的依赖性发生变化时,才会重新生成memorize函数。所以当改变name的状态是addage不会变化。
4、userefuseref类似于react.createref。
const node = useref(initref)
useref 返回一个可变的 ref 对象,其 current 属性被初始化为传入的参数(initref)
作用在dom上
const node = useref(null)<input ref={node} />
这样可以通过node.current属性访问到该dom元素。
需要注意的是useref创建的对象在组件的整个生命周期内保持不变,也就是说每次重新渲染函数组件时,返回的ref 对象都是同一个(使用 react.createref ,每次重新渲染组件都会重新创建 ref)。
5、usereducerusereducer类似于redux中的reducer。
语法
const [state, dispatch] = usereducer(reducer, initstate)
usereducer传入一个计算函数和初始化state,类似于redux。通过返回的state我们可以访问状态,通过dispatch可以对状态作修改。
const initstate = 0;function reducer(state, action) { switch (action.type) { case 'increment': return {number: state.number + 1}; case 'decrement': return {number: state.number - 1}; default: throw new error(); }}function counter(){ const [state, dispatch] = usereducer(reducer, initstate); return ( <> count: {state.number} <button onclick={() => dispatch({type: 'increment'})}>+</button> <button onclick={() => dispatch({type: 'decrement'})}>-</button> </> )}
6、usecontext通过usecontext我们可以更加方便的获取上层组件提供的context。
父组件
import react, { createcontext, children } from 'react'import child from './child'export const mycontext = createcontext()export default function parent() { return ( <div> <p>parent</p> <mycontext.provider value={{name: 'cc', age: 21}}> <child /> </mycontext.provider> </div> )}
子组件
import react, { usecontext } from 'react'import { mycontext } from './parent'export default function parent() { const data = usecontext(mycontext) // 获取父组件提供的context console.log(data) return ( <div> <p>child</p> </div> )}
使用步骤
父组件创建并导出context:export const mycontext = createcontext()父组件使用provider和value提供值:<mycontext.provide value={{name: 'cc', age: 22}} />子组件导入父组件的context:import { mycontext } from './parent'获取父组件提供的值:const data = usecontext(mycontext)不过在多数情况下我们都不建议使用context,因为会增加组件的耦合性。
7、uselayouteffectuseeffect 在全部渲染完毕后才会执行;uselayouteffect 会在 浏览器 layout之后,painting之前执行,并且会柱塞dom;可以使用它来读取 dom 布局并同步触发重渲染。
export default function layouteffect() { const [color, setcolor] = usestate('red') uselayouteffect(() => { alert(color) // 会阻塞dom的渲染 }); useeffect(() => { alert(color) // 不会阻塞 }) return ( <> <div id="mydiv" style={{ background: color }}>颜色</div> <button onclick={() => setcolor('red')}>红</button> <button onclick={() => setcolor('yellow')}>黄</button> </> )}
上面的例子中uselayouteffect会在painting之前执行,useeffect在painting之后执行。
hooks让函数组件拥有了内部状态、生命周期,使用hooks让代码更加的简介,自定义hooks方便了对逻辑的复用,并且摆脱了class组件的this问题;但是在使用hooks时会产生一些闭包问题,需要仔细使用。
【相关推荐:redis视频教程】
以上就是react hook和class的区别有哪些的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录