4、将函数转换为类
你可以通过5个步骤将函数组件 Clock
转换为类
-
创建一个名称扩展为
React.Component
的ES6 类 -
创建一个叫做
render()
的空方法 -
将函数体移动到
render()
方法中 -
在
render()
方法中,使用this.props
替换props
-
删除剩余的空函数声明
函数:
function Clock(props) {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {props.date.toLocaleTimeString()}.</h2>
</div>
);
}
类:
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
5、正确地使用状态
关于 setState()
这里有三件事情需要知道
-
不要直接更新状态
构造函数是唯一能够初始化
this.state
的地方// Wrong this.state.comment = 'Hello'; // Correct this.setState({comment: 'Hello'});
状态更新可能是异步的
-
React 可以将多个
setState()
调用合并成一个调用来提高性能。因为
this.props
和this.state
可能是异步更新的,你不应该依靠它们的值来计算下一个状态。// Wrong this.setState({ counter: this.state.counter + this.props.increment, }); // Correct this.setState((prevState, props) => ({ counter: prevState.counter + props.increment })); // Correct this.setState(function(prevState, props) { return { counter: prevState.counter + props.increment }; });
注意:箭头函数是ES6的一种语法,其基本的语法为:
(参数1, 参数2, …, 参数N) => { 函数声明 } //相当于:(参数1, 参数2, …, 参数N) =>{ return 表达式; } (参数1, 参数2, …, 参数N) => 表达式(单一) // 当只有一个参数时,圆括号是可选的: (单一参数) => {函数声明} 单一参数 => {函数声明} // 没有参数的函数应该写成一对圆括号。 () => {函数声明}
-
状态更新合并
当你调用 setState()
时,React 将你提供的对象合并到当前状态。
例如,你的状态可能包含一些独立的变量:
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
你可以调用 setState()
独立地更新它们:
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
这里的合并是浅合并,也就是说this.setState({comments})
完整保留了this.state.posts
,但完全替换了this.state.comments
。