继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【九月打卡】第18天 实际工作,做过哪些react优化?

一米阳光0704
关注TA
已关注
手记 23
粉丝 11
获赞 7

第一模块(课程信息):

课程名称:2周刷完100道前端优质面试真题
课程章节:第七章第十节 实际工作中,你做过哪些react优化?
主讲老师:双越

第二模块(课程内容):

课程内容概述

一、使用css模拟v-show

{!flag&&<MyComponent style={{display:'none'}} />}
{flag&&<MyComponent />}
<MyComponent style={{display: flag?'block':'none'}} />

二、循环要使用key

const todoItems = todos.map((todo)=>{
    // key不要用index
	<li key={todo.id}>
      {todo.text}
    </li>
})

三、使用Fragment减少层级

render(){
	return <>
		<p>hello</p>
		<p>world</p>
  <>
}

四、JSX中不要定义函数

{/* bad */}
<Button onClick={()=>{...}}>点击</Button>
{/* good */}
class MyComponent extends React.Component{
	clickHandler(){
	}
	render(){
	    return <>
			<Button onClick={this.clickHandler}>点击</Button>
       </>
    }
}

五、构造函数中绑定this

class MyComponent extends React.Component{
    constructor(){
	    this.handleClicker1 = this.handleClicker1.bind(this);
    }
    // 如果jsx中直接使用,则this不是当前组件,因此要bind this
	handleClicker1(){}
	// 使用箭头函数,不用bind this
	handleClicker2 = () =>{}
	render(){
	    return <>
			<Button onClick={this.handleClicker1}>点击</Button>
       </>
    }
}

六、正确使用shouldComponentUpdate

  • 使用shouldComponentUpdate判断是否需要更新
  • 使用React.PureComponent
  • 使用React.memo

注意:
1、react中不可变数据,使用concat连接数据(不修改原数据),不要用push(push会修改原数据)
2、react默认会让所有的子组件都更新,无论涉及的数据是否变化
3、PureComponent方法中不可再使用shouldComponentUpdate

七、hooks缓存数据和函数

  • useMemo
  • useCallback

温馨提示:
不可变数据可以使用immer第三方库

常睬的坑总结:

1、自定义组件的名称首字母要大写(vue无此要求)

{/* 原生html组件 */}
<input />

{/* 自定义组件 */}
<Input />

2、JS关键词的冲突

{/* for改成htmlFor, class要改为className */}
<label htmlFor="input-name" className="xxx">
	姓名<input id="input-name" />
</label>

3、JSX的数据类型

<Demo position={1} flag={true} />
<Demo position="1" flag="true" />

4、setState是异步更新

const curNum = this.state.num;
this.setState({
	num: curNum+1
},()=>{
	console.log('newNum',this.state.num); //正确,拿到变化后的值
})

第三模块(学习心得):

通过课程的学习,系统的学习了使用react开发过程中,会经常遇到的一些坑,在开发中更加注意。

第四模块(学习截图):

图片描述
图片描述
图片描述
图片描述

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP