菜鸟教程 -- 学的不仅是技术,更是梦想!

React 教程
(追記) (追記ここまで)

React 组件 API

React 组件 API 涉及多个重要的方面,包括生命周期方法、状态管理、属性传递和事件处理。

以下是 React 组件 API 的详细说明:

生命周期方法

React 组件的生命周期方法分为三个主要阶段:挂载、更新和卸载,详细说明参见:React 组件的生命周期

挂载阶段

  • constructor(props): 构造函数,用于初始化状态或绑定方法。
  • static getDerivedStateFromProps(props, state): 每次在调用 render 方法之前调用,用于更新状态。
  • componentDidMount(): 组件挂载后调用,此时可以进行 DOM 操作或数据请求。

实例

class MyComponent extends React.Component {
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>;
}
}

更新阶段

  • static getDerivedStateFromProps(props, state): 与挂载阶段相同,用于更新状态。
  • shouldComponentUpdate(nextProps, nextState): 返回布尔值,决定组件是否重新渲染。
  • render(): 渲染组件的 UI。
  • getSnapshotBeforeUpdate(prevProps, prevState): 在 DOM 更新之前调用,用于捕获一些信息(如滚动位置)。
  • componentDidUpdate(prevProps, prevState, snapshot): 在组件更新后调用。

实例

class MyComponent extends React.Component {
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>;
}
}

卸载阶段

  • componentWillUnmount(): 组件即将卸载时调用,用于清理资源(如定时器、事件监听等)。

实例

class MyComponent extends React.Component {
componentWillUnmount() {
console.log('Component will unmount');
}

render() {
return <div>{this.state.count}</div>;
}
}

状态管理

状态是一个组件内部的数据,使用 this.state 来定义和管理。通过 setState 方法更新状态。

实例

class MyComponent extends React.Component {
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>
);
}
}

属性传递

通过 this.props 访问传递给组件的属性,可以使用 PropTypes 进行类型检查。

实例

import PropTypes from 'prop-types';

class MyComponent extends React.Component {
render() {
return <div>{this.props.title}</div>;
}
}

MyComponent.propTypes = {
title: PropTypes.string.isRequired,
};

// 使用组件并传递属性
<MyComponent title="Hello, World!" />

事件处理

通过事件处理函数处理用户交互。需要使用 .bind(this) 或箭头函数来确保 this 指向正确。

实例

class MyComponent extends React.Component {
handleClick = () => {
console.log('Button clicked');
};

render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}

条件渲染

通过条件语句控制组件的渲染。

实例

class MyComponent extends React.Component {
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>
);
}
}

列表渲染

通过数组的 map 方法渲染列表。

实例

class MyComponent extends React.Component {
render() {
const items = ['Item 1', 'Item 2', 'Item 3'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
}

受控组件

通过状态控制表单元素的值。

实例

class MyComponent extends React.Component {
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>
);
}
}

设置状态:setState

setState 是 React 中用于更新组件状态的方法。

语法格式如下:

setState(object nextState[, function callback])

参数说明

  • object nextState: 一个对象,包含要更新的状态键值对。React 会将这个对象合并到当前状态中。
  • function callback: 一个可选的回调函数,会在状态更新并重新渲染完成后执行。

合并 nextState 和当前 state,并重新渲染组件。

setState 是 React 事件处理函数中和请求回调函数中触发 UI 更新的主要方法。

关于setState

不能在组件内部通过 this.state 修改状态,因为该状态会在调用 setState() 后被替换。

setState() 并不会立即改变 this.state,而是创建一个即将处理的 state。setState() 并不一定是同步的,为了提升性能 React 会批量执行 state 和 DOM 渲染。

setState()总是会触发一次组件重绘,除非在 shouldComponentUpdate() 中实现了一些条件渲染逻辑。

通过合理使用 setState,可以有效地管理组件状态,并确保在状态更新后执行必要的操作,从而提高应用的响应性和可靠性。

React 实例

classCounterextendsReact.Component{constructor(props){super(props); this.state = {clickCount: 0}; this.handleClick = this.handleClick.bind(this); }handleClick(){this.setState(function(state){return{clickCount: state.clickCount + 1}; }); }render(){return(<h2onClick={this.handleClick}>点我!点击次数为: {this.state.clickCount}</h2>); }}constroot = ReactDOM.createRoot(document.getElementById("root")); root.render( <Counter /> );

尝试一下 »

实例中通过点击 h2 标签来使得点击计数器加 1。

AI 思考中...

2 篇笔记 写笔记

  1. #0

    疾风拂晓

    101***[email protected]

    参考地址

    120

    关于 setState() 这里有三件事情需要知道。

    1、不要直接更新状态

    例如,此代码不会重新渲染组件:

    // Wrong
    this.state.comment = 'Hello';

    应当使用 setState():

    // Correct
    this.setState({comment: 'Hello'});

    构造函数是唯一能够初始化 this.state 的地方。

    2、状态更新可能是异步的

    React 可以将多个 setState() 调用合并成一个调用来提高性能。

    因为 this.props 和 this.state 可能是异步更新的,你不应该依靠它们的值来计算下一个状态。

    例如,此代码可能无法更新计数器:

    // Wrong
    this.setState({
     counter: this.state.counter + this.props.increment,
    });

    要修复它,请使用第二种形式的 setState() 来接受一个函数而不是一个对象。 该函数将接收先前的状态作为第一个参数,将此次更新被应用时的props做为第二个参数:

    // Correct
    this.setState((prevState, props) => ({
     counter: prevState.counter + props.increment
    }));

    上方代码使用了箭头函数,但它也适用于常规函数:

    // Correct
    this.setState(function(prevState, props) {
     return {
     counter: prevState.counter + props.increment
     };
    });

    3、状态更新合并

    当你调用 setState() 时,React 将你提供的对象合并到当前状态。

    例如,你的状态可能包含一些独立的变量:

    constructor(props) {
     super(props);
     this.state = {
     posts: [],
     comments: []
     };
     }

    你可以调用 setState() 独立地更新它们:

    componentDidMount() {
     fetchPosts().then(response => {
     this.setState({
     posts: response.posts
     });
     });
     fetchComments().then(response => {
     this.setState({
     comments: response.comments
     });
     });
     }

    这里的合并是浅合并,也就是说 this.setState({comments}) 完整保留了 this.state.posts,但完全替换了 this.state.comments。

    疾风拂晓

    101***[email protected]

    参考地址

    8年前 (2019年01月20日)
  2. #0

    lujin

    luj***[email protected]

    85

    isMounted 的方法在 ES6 中已经废除。主要的原因是它经过实际使用与测试可能不足以检测组件是否挂载,尤其是对于有一些异步的程序情况,以及逻辑上造成混乱。现在用以下方法代替:

    componentDidMount() {
     this.mounted = true;
    }
    componentWillUnmount() {
     this.mounted = false;
    }

    lujin

    luj***[email protected]

    7年前 (2019年02月24日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /