- 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
}));
网友评论