美文网首页React
004|React之State

004|React之State

作者: 中年小钢炮 | 来源:发表于2017-06-06 19:25 被阅读33次

在JSX中,每一个组件除了props属性外,还有一个state属性。注意state全部为小写。

例如,下面的代码中,在constructor中初始化state,然后在render中引用state:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()}; // 初始化
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2> // 引用 
      </div>
    );
  }
}

state有一些要点要注意。首先,不要直接修改state对象,而要通过setState方法。直接修改state对象不会触发重新绘制。

// Wrong
this.state.comment = 'Hello';

// Correct
this.setState({comment: 'Hello'});

为了性能,React有可能将多个setState合并为一个setState调用。这会导致state、props异步,从而以下调用出错:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

使用setState的函数模式,即可蔽免这个问题:

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

State的一级属性可以通过setState单独更新,如:

constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
    this.setState({
        posts: response.posts
      }); // 只更新posts属性,而comments属性依旧会保留
  }

组件加载与卸载

如果实现了componentDidMount方法,则当组件被加载时,此方法会被调用。

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

如果实现了componentWillUnmount方法,则当组件被卸载时,此方法会被调用。

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

组件中如何处理事件?

好,这一节就到这里。后续我将逐步介绍React技术细节,来慢慢解答上述问题。

想学计算机技术吗?需要1对1专业级导师指导吗?想要团队陪你一起进步吗?欢迎加我为好友!微信号:iTekka。

相关文章

  • 004|React之State

    在JSX中,每一个组件除了props属性外,还有一个state属性。注意state全部为小写。 例如,下面的代码中...

  • React之State

    State 如何组织数据是程序的最重要问题。Raect组件的数据分为两种:prop和state。无论prop还是s...

  • react之state

    在vue中,在不考虑vuex的时候,组件的数据来源有两个, props和data。而在react中组件的数据来源也...

  • react学习笔记--state以及setState

    在react中通过state以及setState() 来控制组件的状态。 state state 是 react ...

  • React Native 学习之路

    React 相关资料 React Components React Properties React State ...

  • react源码剖析——(二)解密setState机制

    state是React中重要的概念。总所周知,React通过this.state来访问state,通过this.s...

  • React hooks之useRef

    接react hooks之effect、state[https://www.jianshu.com/p/b493a...

  • React基础

    react 教程 react 组件介绍 react state 介绍 react Props 介绍 React:组...

  • React之状态(State)

    在React当中,当你更新组件的state,然后新的state就会重新渲染到页面中。在这个时候不需要你操作任何DO...

  • 浅谈react中的state和props

    1、state的作用 state是React中组件的一个对象,React中,更新组件的state,会导致重新渲染用...

网友评论

    本文标题:004|React之State

    本文链接:https://www.haomeiwen.com/subject/djdnfxtx.html