不要直接更新状态
例如,此代码不会重新渲染组件:
// Wrongthis.state.comment = 'Hello'
应当使用 setState():
// Correctthis.setState({ comment: 'Hello' })
setState() 函数是唯一能够更新 this.state 的地方。
状态更新一定是异步的
Taro 可以将多个 setState() 调用合并成一个调用来提高性能。
因为 this.state 和 props 一定是异步更新的,所以你不能在 setState 马上拿到 state 的值,例如:
// 假设我们之前设置了 this.state.counter = 0updateCounter () {this.setState({counter: 1})console.log(this.state.counter) // 这里 counter 还是 0}
正确的做法是这样,在 setState 的第二个参数传入一个 callback:
// 假设我们之前设置了 this.state.counter = 0updateCounter () {this.setState({counter: 1}, () => {// 在这个函数内你可以拿到 setState 之后的值})}
这是 Taro 和 React 另一个不同的地方:React 的
setState不一定总是异步的,他内部有一套事务机制控制,且 React 15/16 的实现也各不相同。而对于 Taro 而言,setState之后,你提供的对象会被加入一个数组,然后在执行下一个 eventloop 的时候合并它们。
state 更新会被合并
当你调用 setState(),Taro 将合并你提供的对象到当前的状态中。
例如,你的状态可能包含几个独立的变量:
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 的值。
