React Component API
The React Component API covers several important aspects, including lifecycle methods, state management, props passing, and event handling.
The following is a detailed description of the React Component API:
Lifecycle Methods
The lifecycle methods of React components are divided into three main phases: mounting, updating, and unmounting. See the detailed description at:React Component Lifecycle 。
Mounting Phase
constructor(props): The constructor, used to initialize state or bind methods.static getDerivedStateFromProps(props, state): Called before the render method is invoked each time, used to update state.componentDidMount(): Called after the component is mounted; DOM operations or data requests can be performed at this point.
Example
constructor(props) {
super(props);
this.state = { count: 0 };
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.reset) {
return { count: 0 };
}
return null;
}
componentDidMount() {
console.log('Component mounted');
}
render() {
return <div>{this.state.count}</div>;
}
}
Updating Phase
static getDerivedStateFromProps(props, state): Same as the mounting phase, used to update state.shouldComponentUpdate(nextProps, nextState): Returns a boolean value that determines whether the component should re-render.render(): Renders the component's UI.getSnapshotBeforeUpdate(prevProps, prevState): Called before the DOM is updated, used to capture some information (such as scroll position).componentDidUpdate(prevProps, prevState, snapshot): Called after the component has been updated.
Example
shouldComponentUpdate(nextProps, nextState) {
return nextState.count !== this.state.count;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
return { scrollPosition: window.scrollY };
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (snapshot) {
window.scrollTo(0, snapshot.scrollPosition);
}
console.log('Component updated');
}
render() {
return <div>{this.state.count}</div>;
}
}
Unmounting Phase
componentWillUnmount(): Called when the component is about to be unmounted, used to clean up resources (such as timers, event listeners, etc.).
Example
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return <div>{this.state.count}</div>;
}
}
State Management
State is the data inside a component, usethis.stateto define and manage it. Use thesetStatemethod to update the state.
Example
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
Props Passing
Access the props passed to the component via this.props; PropTypes can be used for type checking.
Example
class MyComponent extends React.Component {
render() {
return <div>{this.props.title}</div>;
}
}
MyComponent.propTypes = {
title: PropTypes.string.isRequired,
};
// Use the component and pass props
<MyComponent title="Hello, World!" />
Event Handling
Handle user interactions through event handler functions. You need to use .bind(this) or arrow functions to ensure this points to the correct context.
Example
handleClick = () => {
console.log('Button clicked');
};
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
Conditional Rendering
Control component rendering through conditional statements.
Example
constructor(props) {
super(props);
this.state = { isVisible: true };
}
toggleVisibility = () => {
this.setState((prevState) => ({ isVisible: !prevState.isVisible }));
};
render() {
return (
<div>
{this.state.isVisible && <p>This is visible</p>}
<button onClick={this.toggleVisibility}>Toggle</button>
</div>
);
}
}
List Rendering
Render lists using the array's map method.
Example
render() {
const items = ['Item 1', 'Item 2', 'Item 3'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
}
Controlled Components
Control the values of form elements through state.
Example
constructor(props) {
super(props);
this.state = { value: '' };
}
handleChange = (event) => {
this.setState({ value: event.target.value });
};
handleSubmit = (event) => {
event.preventDefault();
console.log('Submitted value:', this.state.value);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<button type="submit">Submit</button>
</form>
);
}
}
Setting State: setState
setState is the method in React used to update component state.
The syntax is as follows:
setState(object nextState[, function callback])
Parameter Description
object nextState: An object containing the key-value pairs of the state to update. React will merge this object into the current state.function callback: An optional callback function that executes after the state has been updated and re-rendering is complete.
Merge nextState with the current state and re-render the component.
setState is the primary method for triggering UI updates in React event handlers and request callback functions.
About setState
You cannot modify state via this.state inside a component, because that state will be replaced after setState() is called.
setState() does not immediately change this.state; instead, it creates a state that is about to be processed. setState() is not necessarily synchronous; to improve performance, React will batch-execute state changes and DOM rendering.
setState() will always trigger a re-render of the component, unless some conditional rendering logic is implemented in shouldComponentUpdate().
By using setState properly, you can effectively manage component state and ensure necessary operations are executed after state updates, thereby improving the responsiveness and reliability of the application.
React Example
Try it »
In the example, clicking the h2 tag increments the click counter by 1.
Other Extensions