react是由facebook公司推出的,主打的口号就是高性能。那么我们在使用的时候,如果能在做一下优化的,那么react使用的性能会更高,用户体验也会更好。
下面我就列出几种优化的方案供大家参考一下
1. setState的优化
16.0更新以后,setSate书写的时候,可以直接穿一个带两个参数的函数,使得我们在重新修改state中值不用再定义变量来接收,直接和原来的值比较就可以了
this.setState((prev) => ({ list: [...prev.list, prev.inputValue], inputValue: '' }))
2.props的值
props接收的值使用es6解构的方式来接收
const { list,name } = this.props
3. ajax请求的位置
定义的事件修改this指向的时候,不建议写在jsx中,而是写到 constructor里面
constructor(props) { super(props) this.handleClick = this.handleClick.bind(this) } render() { const { item } = this.props return ( <div> <div onClick={this.handleClick}>{item}</div> </div> ) }
4.如果组件里面没有逻辑处理的话,只是显示一些UI效果的话,可以把组件改为无状态组件,需要展示的数据和方法直接接受父组件传过来的就可以了
import React, { Fragment } from 'react';
import 'antd/dist/antd.css'
import {Input,Button,List} from 'antd'
const TodoListUI=(props)=>{
return (
<Fragment>
<div className="form-box">
<Input placeholder="请输入" value={props.inputValue} onChange={props.handleChange}style={{'300px'}}/>
<Button type="primary" style={{marginLeft:'20px'}} onClick={props.handleSubmit}>提交</Button>
</div>
<div className="list">
<List
size="small"
bordered
dataSource={props.list}
renderItem={(item,index) => (<List.Item onClick={()=>{props.handleDelete(index)}}>{item}</List.Item>)}
/>
</div>
</Fragment>
)
}
export default TodoListUI;