开始写一个组件时如何判断哪些数据是需要写入state
的?
- 是由父组件通过
props
传递进来的吗? - 是否值永远都不会变化?
- 是否可以通过其他
state
或props
计算得出?
如果有以上一种情况是肯定回答,这个值就可以不用作为state
写入
不可以直接修改state
// 错误
this.state.comment = 'Hello';
//使用setState代替
// 正确
this.setState({comment: 'Hello'});
state
的更新有可能是异步的
this.props
和this.state
同时更新时,结果就不可靠了
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
setState()
第二种写法,可以接收一个函数,函数的第一个参数是是更新前的state
,当前更新的props
作为第二个参数
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
state
可以合并更新
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
单独更新后,结果可以合并
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
单向数据流
各组件之间互相不知晓对方是 stateful or stateless
,也不关心对方是个function or class
,数据只是靠props
向下传递
本章示例
通过定时器设置state
,利用生命周期执行定时器,成功设置一个显示时间的demo
import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount () {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount () {
clearInterval(this.timerID);
}
tick(){
this.setState({
date:new Date()
})
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}</h2>
</div>
);
}
}
render(<App />, document.getElementById('root'));