React 开发时遇到的问题总结

Stateless Component

和普通的 Component 相比,Stateless Component 没有自己的 state,通常用以下函数方式定义
(Eslint prefer-stateless-function 规则)

1
const Home = (props) => <h2>This is our {props.title}</h2>

Stateless Component 主要是展示作用

React 一个组件只能返回一个根节点

这个问题很有意思,实际上不是 React 的问题

1
2
3
4
// jsx
render() {
return <div>hello</div><div>world</div>
}
1
2
3
4
// under the hood
render() {
return React.createElement("div", null) React.createElement("div", null)
}

其实就是一个方法不可能有两个返回值😊

super() 和 super(props) 的区别

问题1:在 Component 的 constructor 中为什么需要调用 super()?
这是 ES6 关于 Class 的概念:

子类的构造器必须调用 super()
在子类的 constructor 中,只有调用了 super,才可以使用 this 作用域

ES6 Class super

问题2:component constructor 中调用 super() 和 super(props) 的区别?
我们知道,在 component 构造方法的外围,可以直接使用 props,只有一种情况下需要在 constructor 中调用 super(props):

当在 constructor 中需要使用 props 的时候

然而,注意,在 React 官方文档中有这么一句

Class components should always call the base constructor with props.

Difference Between super() and super(props)
React ES6 class constructor super()

component 中事件绑定 this 的几种方式

我们经常看到下面这些绑定 this 的代码

1
2
3
4
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}

或者

1
onChange={this.handleChange.bind(this)}

亦或者

1
onChange={e => this.handleChange(e)}

原来 React.createClass 会自动绑定 this,但是使用 ES6 Class 定义 component 后,必须手动绑定 this

5 approaches to handle binding this

Component 生命周期几个关键 Hooks

componentWillMount
componentWillMount 发生在 render 方法之前,所以当在此数 setState 不会触发 re-render

componentDidMount
componentDidMount 在 component render 方法之后执行,通常在此处进行 Ajax 请求,当 setState 触发时,ComponentDidMount 不会被重新执行

componentWillUpdate
componentDidUpdate

componentWillUpdate(prevProps, prevState),componentDidUpdate(prevProps, prevState) 在其 props 所属父元素触发 re-render 或自己触发 setState 进行 re-render 时,都会被执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// App.js
onclick() {
this.stateState({
// ...
});
}

<div>
<Box name="i am a box" />
<h2>I am an app</h2>
<button onClick={this.onclick}>change app state</button>
</div>

// Box.js
<div>{this.props.name}</div>

当点击 button 时,会触发 App Component 和 Box Component 的以下事件(第二个红框),注意顺序:

image