渲染列表
例如有如下数组:['11','22','33']
在react中可以用数组的map方法:
import React, { Component } from 'react'
export default class App extends Component {
constructor(props){
super(props)
this.state = {
list: ['11','22','33'],
}
}
render() {
return (
<div>
<ul>
{
this.state.list.map((item,index) => {
// 传入index
return <li key={index}>{item}</li>
})
}
</ul>
</div>
)
}
}
这里为了方便所以绑定的key值是数组的下标,实际使用中不建议这么做,因为React中Diff算法进行组件对比时,调用的key是数组下标的话,数组的改变,会导致下标对应的数组内容不正确。
代码优化:封装一个渲染方法
import React, { Component } from 'react'
export default class Todolist extends Component {
constructor(props){
super(props)
this.state = {
list: ['11','22','33'],
}
}
getTodoList(){
return (
this.state.list.map((item,index) => {
return <li key={index}>{item}</li>
})
)
}
render() {
return (
<div>
<ul>
{ this.getTodoList() }
</ul>
</div>
)
}
}
添加点击事件
import React, { Component } from 'react'
class App extends React.Component<any, any> {
handleClick2;
constructor(props) {
super(props);
this.state = {
num: 1,
title: ' react study'
};
this.handleClick2 = this.handleClick1.bind(this);
}
handleClick1() {
this.setState({
num: this.state.num + 1,
})
}
handleClick3 = () => {
this.setState({
num: this.state.num + 1,
})
};
render() {
return (<div>
<h2>Ann, {this.state.num}</h2>
<button onClick={this.handleClick2}>btn1</button>
<button onClick={this.handleClick1.bind(this)}>btn2</button>
<button onClick={() => this.handleClick1()}>btn3</button>
<button onClick={this.handleClick3}>btn4</button>
</div>)
}
}
前提:子组件内部做了性能优化,如(React.PureComponent)
- 第一种是在构造函数中绑定 this:那么每次父组件刷新的时候,如果传递给子组件其他的 props 值不变,那么子组件就不会刷新;
- 第二种是在 render() 函数里面绑定 this:因为 bind 函数会返回一个新的函数,所以每次父组件刷新时,都会重新生成一个函数,即使父组件传递给子组件其他的 props 值不变,子组件每次都会刷新;
- 第三种是使用箭头函数:父组件刷新的时候,即使两个箭头函数的函数体是一样的,都会生成一个新的箭头函数,所以子组件每次都会刷新;
- 第四种是使用类的静态属性:原理和第一种方法差不多,比第一种更简洁
综上所述,如果不注意的话,很容易写成第三种写法,导致性能上有所损耗。
js中bind、call、apply都能改变this指向,区别就是bind不会立即调用,而call、apply会立即调用前面的那个函数,bind的第一个参数用来修改this指向,后面所有的参数都会用来当作调用前面函数时候的参数传递进去。