React

004|React之State

2017-06-06  本文已影响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。

上一篇下一篇

猜你喜欢

热点阅读