美文网首页
State and Lifecycle

State and Lifecycle

作者: bestCindy | 来源:发表于2020-08-13 13:08 被阅读0次
  • State is similar to props, but it is private and fully controlled by the component
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
  • The render method will be called each time an update happens, but as long as we render <Clock /> in to the same DOM node, only a single instance of the Clock class will be used. This lets us use additional features such as local state and lifecycle methods.
  • The componentDidMount() method runs after the component output has been rendered to the DOM
  • React calls componentWillUnmount() to tear down the component from the DOM
  • When you invoke setState() method, React knows the state has canged, and calls the render() method again to learn what should be on the screen, and this time, the value of this.state is the newes value
some important points when using State
  • the only place where you can assign this.state is the constructor
  • if you modify State directly, the dom will not re-render, instead you should use setState
  • State updates may be asychronus
  • To fix it, use a second form of setState() that accepts a function rather than an object
this.setState((state, props) => ({
    counter: state.counter  +  props.increment
}));

相关文章

网友评论

      本文标题:State and Lifecycle

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