正确的使用state

开始写一个组件时如何判断哪些数据是需要写入state的?

  • 是由父组件通过props传递进来的吗?
  • 是否值永远都不会变化?
  • 是否可以通过其他stateprops计算得出?

如果有以上一种情况是肯定回答,这个值就可以不用作为state写入

不可以直接修改state

// 错误
this.state.comment = 'Hello';
//使用setState代替
// 正确
this.setState({comment: 'Hello'});

state的更新有可能是异步的

this.propsthis.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'));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值