react入门(第二篇)

4、将函数转换为类

你可以通过5个步骤将函数组件 Clock 转换为类

  1. 创建一个名称扩展为 React.ComponentES6 类

  2. 创建一个叫做render()的空方法

  3. 将函数体移动到 render() 方法中

  4. render() 方法中,使用 this.props 替换 props

  5. 删除剩余的空函数声明

函数:

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.propsthis.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值