1、State is similar to props, but it is private and fully controlled by the component.
2、class name extends React.Component
3、The render
method will be called each time an update happens,
but as long as we render <Clock />
into 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.
4、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> ); }
}
Class components should always call the base constructor with
props
.
5、Do Not Modify State Directly,The only place where you can assign
this.state
is the constructor.
6、State Updates May Be Asynchronous
React may batch multiple setState()
calls into a single update for performance.
Because this.props
and this.state
may be updated asynchronously, you should not rely on their values for calculating the next state.
To fix it, use a second form of setState()
that accepts a function rather than an object.
That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
// Correct this.setState((state, props) => ({ counter: state.counter + props.increment }));
You have to be careful about the meaning of
7、this
in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bindthis.handleClick
and pass it toonClick
,this
will beundefined
when the function is actually called.
This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without ()
after it, such as onClick={this.handleClick}
, you should bind that method.
8、We don’t recommend using indexes for keys if the order of items may change.
This can negatively impact performance and may cause issues with component state.
Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key.
If you choose not to assign an explicit key to list items then React will default to using indexes as keys.
9、Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:
10、In HTML, a<textarea>
element defines its text by its children:
In React, a<textarea>
uses avalue
attribute instead. This way, a form using a<textarea>
can be written very similarly to a form that uses a single-line input: