找回密码
 立即注册
首页 业界区 业界 react 知识点汇总(非常全面)

react 知识点汇总(非常全面)

马璞玉 2025-6-6 16:50:29
React 是一个用于构建用户界面的 JavaScript 库,由 Facebook 开发并维护。它的核心理念是“组件化”,即将用户界面拆分为可重用的组件。
React 的组件通常使用 JSX(JavaScript XML)。JSX 是一种 JavaScript 语法扩展,允许开发者在 JavaScript 代码中编写类似 HTML 的结构。
1、初识react

1.1 常用命令

首先安装  Nodejs,然后执行下面命令安装 react
  1. npm i -g create-react-app
复制代码
  1. create-react-app myreact # 创建react项目
  2. npm start # 在项目中输入,启动项目
复制代码
1.2 项目结构

项目创建后有很多文件,一般我们只需保留下面的就行.

  • index.html:应用的主 HTML 文件,React 应用的根组件通常挂载在此文件中的一个  元素上。
  • index.css:全局样式文件。
  • index.js:应用的入口文件,负责渲染根组件并将其挂载到 index.html 中的 DOM。
  • package.json: 包含项目的元数据(如名称、版本、描述等)、依赖包列表和脚本命令(如 start、build、test)。
  1. my-app/
  2. ├── node_modules/
  3. ├── public/
  4. │   ├── favicon.ico
  5. |   ├── index.html
  6. ├── src/
  7. │   ├── index.css
  8. │   ├── index.js
  9. ├── .gitignore
  10. ├── package.json
  11. ├── README.md
  12. └── yarn.lock / package-lock.json
复制代码
2、基本知识点

1. extends Component

在 React 中,extends Component 是用来创建类组件的方式。React 的类组件通过继承 React.Component 来获得组件的基本功能,如状态管理和生命周期方法。以下是一个简单的例子:
  1. import React, { Component } from 'react';
  2. class MyComponent extends Component {
  3.   render() {
  4.     return <h1>Hello, World!</h1>;
  5.   }
  6. }
复制代码

  • Component:是 React 提供的基类,包含了生命周期方法(如 componentDidMount、componentDidUpdate 等)和其他基本功能。
  • render 方法:每个类组件必须实现的一个方法,用于描述 UI 如何渲染。每当组件的 state 或 props 更新时,render 方法会被调用。
    1. render() {
    2.   return (
    3.    
    4.       <h1>Hello, {this.props.name}!</h1>
    5.    
    6.   );
    7. }
    复制代码

    • 返回值:render 方法可以返回一个单一的元素、多个元素(需要用一个父元素包裹)或者 null。

2. React.Fragment

React.Fragment 是一个用于分组多个子元素而不添加额外 DOM 节点的工具。通常,React 要求每个组件必须返回一个单一的根元素,使用 Fragment 可以解决这个问题。示例:
  1. import React from 'react';
  2. class MyComponent extends Component {
  3.   render() {
  4.     return (
  5.       <React.Fragment>
  6.         <h1>Title</h1>
  7.         <p>Some content.</p>
  8.       </React.Fragment>
  9.     );
  10.   }
  11. }
复制代码

  • 语法简化:可以用  和  来简化 Fragment 的使用:
3. className

在 React 中,使用 className 属性来指定一个或多个 CSS 类,而不是使用 HTML 的 class 属性。这是因为 class 是 JavaScript 中的保留关键字,React 采用 className 来避免冲突。
示例:
  1. function MyComponent() {
  2.   return Hello, World!;
  3. }
复制代码
  1. .my-class {
  2.   color: blue;
  3.   font-size: 20px;
  4. }
复制代码
动态类名
  1. function MyComponent({ isActive }) {
  2.   return (
  3.    
  4.       Hello, World!
  5.    
  6.   );
  7. }
复制代码
在这个例子中,如果 isActive 为 true,div 将具有 active 类。
4. {} 的用法

在 JSX 中,{} 用于表示 JavaScript 表达式。你可以在其中嵌入变量、函数调用和其他表达式。
示例:
  1. const name = "Alice";
  2. function Greeting() {
  3.   return <h1>Hello, {name}!</h1>; // 使用 {} 插入变量
  4. }
复制代码
5 jsx 中的 css

1. 基本语法

在 JSX 中,内联样式需要使用 JavaScript 对象的形式定义。具体来说:

  • 样式属性使用驼峰命名法(camelCase)。
  • 属性值通常为字符串或数字(需要附加单位时,使用字符串)。
1.1 示例代码
  1. const MyComponent = () => {
  2.     const style = {
  3.         color: 'blue',
  4.         backgroundColor: 'lightgray',
  5.         padding: '10px',
  6.         fontSize: '16px',
  7.         border: '1px solid black'
  8.     };
  9.     return 这是一个内联样式的组件;
  10. };
复制代码
在这个示例中,我们定义了一个样式对象 style,并将其应用到  元素中。
2. 动态样式

内联样式的一个主要优势是可以很容易地根据组件的状态或属性动态更新样式。例如,可以根据 state 的值来改变样式:
  1. import React, { useState } from 'react';
  2. const DynamicStyleComponent = () => {
  3.     const [isActive, setIsActive] = useState(false);
  4.     const style = {
  5.         color: isActive ? 'white' : 'black',
  6.         backgroundColor: isActive ? 'blue' : 'gray',
  7.         padding: '10px',
  8.         cursor: 'pointer'
  9.     };
  10.     return (
  11.          setIsActive(!isActive)}
  12.         >
  13.             {isActive ? '激活状态' : '非激活状态'}
  14.         
  15.     );
  16. };
复制代码
在这个示例中,点击  会切换其状态,从而改变文字和背景颜色。
3. 优缺点

优点


  • 简单直接:可以快速应用样式,尤其是动态样式时。
  • 无类名冲突:因为样式是局部的,不会受到其他样式的影响。
缺点


  • 不可复用:无法将样式应用于多个组件,难以维护。
  • 性能问题:每次渲染都会创建新的对象,可能会影响性能,特别是在频繁更新的组件中。
  • 不支持伪类和媒体查询:无法使用 CSS 的伪类(如 :hover)和媒体查询,限制了样式的灵活性。
3、Componets 写法

1. React 组件的基本概念

React 组件是构成 React 应用的基本单元。它们可以是类组件或函数组件。类组件使用 ES6 类来定义,而函数组件则是简单的 JavaScript 函数。
1.1 类组件

类组件通常用于需要管理状态或使用生命周期方法的场景。
  1. import React, { Component } from 'react';
  2. class MyComponent extends Component {
  3.     // 构造函数用于初始化 state
  4.     constructor(props) {
  5.         super(props);
  6.         this.state = {
  7.             count: 0
  8.         };
  9.     }
  10.     // 上面 constructor 这块的代码可以只写 state {count : 0},
  11.     // 在类组件中,可以直接在类的主体中定义 state,而不必在构造函数中初始化。
  12.     // 这种语法会自动将 state 绑定到实例上,因此不需要显式调用 super(props)。
  13.     // 增加 count 的方法
  14.     increment = () => {
  15.         this.setState({ count: this.state.count + 1 });
  16.     };
  17.     render() {
  18.         return (
  19.             
  20.                 <h1>{this.state.count}</h1>
  21.                 <button onClick={this.increment}>增加</button>
  22.             
  23.         );
  24.     }
  25. }
  26. export default MyComponent;
复制代码
1.2 函数组件

函数组件是无状态的,可以使用 React Hooks 来管理状态和副作用。
  1. import React, { useState } from 'react';
  2. const MyComponent = () => {
  3.     const [count, setCount] = useState(0); // useState Hook
  4.     const increment = () => {
  5.         setCount(count + 1);
  6.     };
  7.     return (
  8.         
  9.             <h1>{count}</h1>
  10.             <button onClick={increment}>增加</button>
  11.         
  12.     );
  13. };
  14. export default MyComponent;
复制代码
2. State 的管理

state 是组件的本地状态,用于存储组件的动态数据。当状态改变时,React 会自动重新渲染组件。
2.1 设置初始状态

在类组件中,初始状态通常在构造函数中定义;在函数组件中,可以使用 useState Hook。
2.2 修改状态

使用 this.setState(类组件)或状态更新函数(函数组件)来更新状态。重要的是,状态更新是异步的。
  1. // 类组件
  2. this.setState({ key: value });
  3. // 函数组件
  4. setCount(newCount);
复制代码
3. 遍历生成元素

在状态中存储一个数组,然后通过 .map() 方法遍历生成多个元素。
3.1 类组件示例
  1. class ListComponent extends Component {
  2.     constructor(props) {
  3.         super(props);
  4.         this.state = {
  5.             items: ['苹果', '香蕉', '橙子']
  6.         };
  7.     }
  8.     render() {
  9.         return (
  10.             <ul>
  11.                 {this.state.items.map((item, index) => (
  12.                     <li key={index}>{item}</li>
  13.                 ))}
  14.             </ul>
  15.         );
  16.     }
  17. }
复制代码
3.2 函数组件示例
  1. const ListComponent = () => {
  2.     const [items, setItems] = useState(['苹果', '香蕉', '橙子']);
  3.     return (
  4.         <ul>
  5.             {items.map((item, index) => (
  6.                 <li key={index}>{item}</li>
  7.             ))}
  8.         </ul>
  9.     );
  10. };
复制代码
4. 函数传参

4.1 传递参数 e
  1. class MyComponent extends Component {
  2.   handleClick = (e) => {
  3.     console.log(e.target);
  4.   };
  5.   render() {
  6.     return (
  7.       <button onClick={this.handleClick}>        // 传递参数 e
  8.         Click me
  9.       </button>
  10.     );
  11.   }
  12. }
复制代码
4.2 传递自定义参数
  1. class MyComponent extends Component {
  2.   handleClick = (param) => {
  3.     console.log('Button clicked!', param);
  4.   };
  5.   render() {
  6.     return (
  7.       <button onClick={() => this.handleClick('Hello')}>        // 传递自定义参数
  8.         Click me
  9.       </button>
  10.     );
  11.   }
  12. }
复制代码
4.3 传递参数 e 和 自定义参数
  1. class MyComponent extends Component {
  2.   handleClick = (param, e) => {
  3.     console.log('Button clicked!', param);
  4.   };
  5.   render() {
  6.     return (
  7.       <button onClick={(e) => this.handleClick('Hello', e)}>        // 传递参数
  8.         Click me
  9.       </button>
  10.     );
  11.   }
  12. }
复制代码
5. 添加、删除和更新状态

可以通过按钮或其他交互方式来添加、删除或更新状态中的元素。
5.1 添加元素
  1. // 在类组件中
  2. addItem = () => {
  3.     this.setState(prevState => ({
  4.         items: [...prevState.items, '新水果']
  5.     }));
  6. };
  7. // 在函数组件中
  8. const addItem = () => {
  9.     setItems([...items, '新水果']);
  10. };
复制代码
5.2 删除元素
  1. // 在类组件中
  2. removeItem = index => {
  3.     this.setState(prevState => ({
  4.         items: prevState.items.filter((_, i) => i !== index)
  5.     }));
  6. };
  7. // 在函数组件中
  8. const removeItem = index => {
  9.     setItems(items.filter((_, i) => i !== index));
  10. };
复制代码
6. 受控表单绑定
  1. import React, { useState } from 'react';
  2. function ControlledForm() {
  3.   const [name, setName] = useState('');
  4.   const [email, setEmail] = useState('');
  5.   const handleSubmit = (e) => {
  6.     e.preventDefault();
  7.     alert(`Name: ${name}, Email: ${email}`);
  8.   };
  9.   return (
  10.     <form onSubmit={handleSubmit}>
  11.       
  12.         <label>
  13.           Name:
  14.           <input
  15.             type="text"
  16.             value={name}        // 把 name 赋值给value
  17.             onChange={(e) => setName(e.target.value)}                // name 绑定上target.value
  18.           />
  19.         </label>
  20.       
  21.       
  22.         <label>
  23.           Email:
  24.           <input
  25.             type="email"
  26.             value={email}
  27.             onChange={(e) => setEmail(e.target.value)}
  28.           />
  29.         </label>
  30.       
  31.       <button type="submit">Submit</button>
  32.     </form>
  33.   );
  34. }
  35. export default ControlledForm;
复制代码
7. 获取dom元素

1. 函数组件

可以通过 useRef 创建 refs:
  1. import React, { useRef } from 'react';
  2. function FocusInput() {
  3.   const inputRef = useRef(null);       
  4.   const handleFocus = () => {
  5.     inputRef.current.focus(); // 获取到的 DOM 元素调用 focus 方法
  6.   };
  7.   return (
  8.    
  9.       <input type="text" ref={inputRef} />
  10.       <button onClick={handleFocus}>Focus the input</button>
  11.    
  12.   );
  13. }
  14. export default FocusInput;
复制代码

  • useRef: 创建一个 ref,用于存储对 DOM 元素的引用。
  • ref 属性: 将 ref 赋值给要获取的元素,例如 。
  • 访问 DOM 元素: 通过 inputRef.current 来访问 DOM 元素。
2. 类组件

可以通过 React.createRef() 创建 refs:
  1. import React, { Component } from 'react';
  2. class FocusInput extends Component {
  3.   constructor(props) {
  4.     super(props);
  5.     this.inputRef = React.createRef();
  6.   }
  7.   handleFocus = () => {
  8.     this.inputRef.current.focus();
  9.   };
  10.   render() {
  11.     return (
  12.       
  13.         <input type="text" ref={this.inputRef} />
  14.         <button onClick={this.handleFocus}>Focus the input</button>
  15.       
  16.     );
  17.   }
  18. }
  19. export default FocusInput;
复制代码
4、组件之间传递数据

子组件接收到的 props 是不可变的。如果需要修改 props 中的数据,应该通过父组件来管理状态并传递更新的值。
1 - 4 都是 父传子, 5 是 子传父
1. 传递常见数据类型(类组件写法)

在父组件的 state 中存储基本数据类型,并通过 props 传递给子组件。
父组件
  1. import React, { Component } from 'react';
  2. import ChildComponent from './ChildComponent';
  3. class ParentComponent extends Component {
  4.   state = {
  5.           // 基本数据类型
  6.     message: 'Hello from Parent!',
  7.     numberValue: 42,
  8.     boolValue: true,
  9.    
  10.     user: {        // 对象
  11.       name: 'Alice',
  12.       age: 30,
  13.     },
  14.    
  15.   };
  16.   handleAlert = () => {        // 方法
  17.     alert('Hello from Parent!');
  18.   };
  19.   updateBoolValue = () => {
  20.     this.setState(prevState => ({ boolValue: !prevState.boolValue }));
  21.   };
  22.   render() {
  23.     return (
  24.       
  25.         <h1>Parent Component</h1>
  26.         <ChildComponent
  27.           message={this.state.message}
  28.           number={this.state.numberValue}
  29.           isTrue={this.state.boolValue}
  30.          
  31.           user={this.state.user}        // 对象
  32.           showAlert={this.handleAlert}        // 方法
  33.         />
  34.         <button onClick={this.updateBoolValue}>Toggle Boolean</button>
  35.       
  36.     );
  37.   }
  38. }
  39. export default ParentComponent;
复制代码
子组件
  1. import React, { Component } from 'react';
  2. class ChildComponent extends Component {
  3.   render() {
  4.     return (
  5.       
  6.         <h2>Child Component</h2>
  7.         <p>{this.props.message}</p>
  8.         <p>Number: {this.props.number}</p>
  9.         <p>Boolean: {this.props.isTrue ? 'True' : 'False'}</p>
  10.         
  11.         <ChildComponent user={this.state.user} />        // 对象
  12.       
  13.     );
  14.   }
  15. }
  16. export default ChildComponent;
复制代码
2. 传递常见数据类型(函数组件写法)

父组件
  1. import React, { useState } from 'react';
  2. import ChildComponent from './ChildComponent';
  3. const ParentComponent = () => {
  4.   const [message] = useState('Hello from Parent!');
  5.   const [numberValue] = useState(42);
  6.   const [boolValue, setBoolValue] = useState(true);
  7.   const [user] = useState({
  8.     name: 'Alice',
  9.     age: 30,
  10.   });
  11.   const handleAlert = () => {
  12.     alert('Hello from Parent!');
  13.   };
  14.   const updateBoolValue = () => {
  15.     setBoolValue(prev => !prev);
  16.   };
  17.   return (
  18.    
  19.       <h1>Parent Component</h1>
  20.       <ChildComponent
  21.         message={message}
  22.         number={numberValue}
  23.         isTrue={boolValue}
  24.         user={user}
  25.         showAlert={handleAlert}
  26.       />
  27.       <button onClick={updateBoolValue}>Toggle Boolean</button>
  28.    
  29.   );
  30. };
  31. export default ParentComponent;
复制代码
子组件
  1. import React from 'react';
  2. const ChildComponent = ({ message, number, isTrue, user }) => {
  3.   return (
  4.    
  5.       <h2>Child Component</h2>
  6.       <p>{message}</p>
  7.       <p>Number: {number}</p>
  8.       <p>Boolean: {isTrue ? 'True' : 'False'}</p>
  9.       <p>User: {user.name}, Age: {user.age}</p> {/* 对象 */}
  10.    
  11.   );
  12. };
  13. export default ChildComponent;
复制代码
说明

  • 使用 useState 来管理状态。
  • 通过解构 props 直接在函数参数中获取需要的值。
  • 保持功能和逻辑不变,实现了相同的父子组件传值。
3. 传递多个 HTML 结构(类组件)

父组件将多个 JSX 元素传递给子组件,通过 props.children 访问这些元素。
  1. import React, { Component } from 'react';
  2. import ChildComponent from './ChildComponent';
  3. class ParentComponent extends Component {
  4.   render() {
  5.     return (
  6.       
  7.         <h1>Parent Component</h1>
  8.         <ChildComponent>        //  把 html 写在组件子组件当中
  9.           <p>This is the first custom content!</p>
  10.           <p>This is the second custom content!</p>
  11.           <h3>This is a header as custom content!</h3>
  12.         </ChildComponent>
  13.       
  14.     );
  15.   }
  16. }
  17. export default ParentComponent;
复制代码
子组件
在子组件中,我们可以通过 React.Children.map 或者 this.props.children 分别处理传递过来的多个元素。
  1. import React, { Component } from 'react';
  2. class ChildComponent extends Component {
  3.   render() {
  4.     return (
  5.       
  6.         <h2>Child Component</h2>        // children数组中包含了父组件传递的 html
  7.         {React.Children.map(this.props.children, (child, index) => (
  8.           {child}
  9.         ))}
  10.       
  11.     );
  12.   }
  13. }
  14. export default ChildComponent;
复制代码
4. 传递多个 HTML 结构(函数组件)

父组件
  1. import React from 'react';
  2. import ChildComponent from './ChildComponent';
  3. const ParentComponent = () => {
  4.   return (
  5.    
  6.       <h1>Parent Component</h1>
  7.       <ChildComponent>
  8.         <p>This is the first custom content!</p>
  9.         <p>This is the second custom content!</p>
  10.         <h3>This is a header as custom content!</h3>
  11.       </ChildComponent>
  12.    
  13.   );
  14. };
  15. export default ParentComponent;
复制代码
子组件
  1. import React from 'react';
  2. const ChildComponent = ({ children }) => {
  3.   return (
  4.    
  5.       <h2>Child Component</h2>
  6.       {React.Children.map(children, (child, index) => (
  7.         {child}
  8.       ))}
  9.    
  10.   );
  11. };
  12. export default ChildComponent;
复制代码
说明

  • 父组件: 使用函数组件,并将多个 JSX 元素作为子组件的内容传递。
  • 子组件: 通过解构 props 获取 children,并使用 React.Children.map 迭代处理每个子元素。
5. 子传父

父组件
  1. import React, { useState } from 'react';
  2. import ChildComponent from './ChildComponent';
  3. const ParentComponent = () => {
  4.   const [dataFromChild, setDataFromChild] = useState('');
  5.   const handleDataChange = (data) => {
  6.     setDataFromChild(data);
  7.   };
  8.   return (
  9.    
  10.       <h1>Parent Component</h1>
  11.       <p>Data from Child: {dataFromChild}</p>
  12.       <ChildComponent onDataChange={handleDataChange} />
  13.    
  14.   );
  15. };
  16. export default ParentComponent;
复制代码
子组件
  1. import React from 'react';
  2. const ChildComponent = ({ onDataChange }) => {
  3.   const sendDataToParent = () => {
  4.     const data = 'Hello from Child!';
  5.     onDataChange(data); // 调用父组件传来的函数
  6.   };
  7.   return (
  8.    
  9.       <h2>Child Component</h2>
  10.       <button onClick={sendDataToParent}>Send Data to Parent</button>
  11.    
  12.   );
  13. };
  14. export default ChildComponent;
复制代码
说明

  • 父组件: ParentComponent 使用 useState 来存储从子组件接收到的数据,并定义一个 handleDataChange 函数来更新状态。
  • 子组件: ChildComponent 接收 onDataChange 函数作为 prop,点击按钮时调用该函数将数据发送给父组件。
5、生命周期


  • 挂载阶段

    • constructor()
    • render()
    • componentDidMount()

  • 更新阶段

    • getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • componentDidUpdate()

  • 卸载阶段

    • componentWillUnmount()

1. 挂载(Mount)

当组件被创建并插入到 DOM 中时,进入挂载阶段。执行顺序如下:

  • constructor():构造函数用于初始化状态和绑定方法。
  • render():返回要渲染的 JSX,决定组件的结构。
  • componentDidMount():组件挂载后调用,适合进行 API 请求或添加事件监听。
2. 更新(Update)

当组件的状态或属性发生变化时,组件会重新渲染,进入更新阶段。执行顺序如下:

  • render():重新渲染组件。
  • getDerivedStateFromProps(nextProps, prevState):在渲染前调用,可以根据新 props 更新 state。
  • shouldComponentUpdate(nextProps, nextState):用于控制组件是否重新渲染,返回 true 或 false。
  • componentDidUpdate(prevProps, prevState):组件更新后调用,可以根据上一个状态或属性执行副作用。
3. 卸载(Unmount)

当组件从 DOM 中移除时,进入卸载阶段。执行顺序如下:

  • componentWillUnmount():组件卸载前调用,适合清理资源(如取消网络请求或移除事件监听)。
4. 使用 Hook 的方式

在函数组件中,可以使用 Hook 来实现类似的生命周期效果:

  • useEffect:相当于 componentDidMount 和 componentDidUpdate,可以用于处理副作用。
  1. import React, { useEffect, useState } from 'react';
  2. const MyComponent = () => {
  3.   const [count, setCount] = useState(0);
  4.   useEffect(() => {
  5.     // 组件挂载时执行
  6.     console.log('Component mounted');
  7.     // 组件更新时执行
  8.     return () => {
  9.       // 组件卸载时清理
  10.       console.log('Component unmounted');
  11.     };
  12.   }, [count]); // 依赖数组,count 变化时执行
  13.   return (
  14.    
  15.       <p>Count: {count}</p>
  16.       <button onClick={() => setCount(count + 1)}>Increment</button>
  17.    
  18.   );
  19. };
复制代码
6、 路由

1. 基础概念

路由(Routing):在单页应用(SPA)中,路由用于管理不同视图或页面之间的导航。当用户点击链接或按钮时,路由会拦截这些操作,并根据 URL 的变化加载相应的组件,而不需要重新加载整个页面。
React Router:这是最流行的 React 路由库,它提供了灵活的路由功能。React Router 通过组件化的方式来定义和管理路由。
2. 常用组件

React Router 提供了几个核心组件,下面是一些常用的组件及其用途:

  • BrowserRouter:这个组件提供了基于 HTML5 的历史记录的路由。它通常包裹在应用的根组件外部。
    1. import { BrowserRouter } from 'react-router-dom';
    2. function App() {
    3.   return (
    4.     <BrowserRouter>
    5.       {/* 其他组件 */}
    6.     </BrowserRouter>
    7.   );
    8. }
    复制代码
  • Route:用于定义路由的组件。它接受 path 属性来指定匹配的 URL,以及 element 属性来指定渲染的组件。
    1. import { Route } from 'react-router-dom';
    2. <Route path="/about" element={} />
    复制代码
  • Routes:用来包裹多个 Route 组件,确保只有一个匹配的路由被渲染。
    1. import { Routes } from 'react-router-dom';
    2. <Routes>
    3.   <Route path="/" element={<Home />} />
    4.   <Route path="/about" element={} />
    5. </Routes>
    复制代码
  • Link:用于在应用中创建导航链接的组件。它类似于 HTML 的  标签,但使用的是客户端路由。
    1. import { Link } from 'react-router-dom';
    2. <Link to="/about">About</Link>
    复制代码
  • Navigate:用于在组件中进行重定向。
    1. import { Navigate } from 'react-router-dom';
    2. <Navigate to="/home" />
    复制代码
3. 路由配置

配置路由通常涉及创建一个路由表,定义各个路由及其对应的组件。以下是一个简单的示例,展示如何在 React 应用中配置路由。
  1. import React from 'react';
  2. import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
  3. // 导入页面组件
  4. import Home from './Home';
  5. import About from './About';
  6. import NotFound from './NotFound';
  7. function App() {
  8.   return (
  9.     <BrowserRouter>
  10.       <nav>
  11.         <Link to="/">Home</Link>
  12.         <Link to="/about">About</Link>
  13.       </nav>
  14.       <Routes>
  15.         <Route path="/" element={<Home />} />
  16.         <Route path="/about" element={} />
  17.         {/* 404 页面 */}
  18.         <Route path="*" element={<NotFound />} />
  19.       </Routes>
  20.     </BrowserRouter>
  21.   );
  22. }
  23. export default App;
复制代码
4. 嵌套路由 及 路由守卫、404

嵌套路由允许你在某个父路由的组件内部定义子路由。这样,你可以在父路由的页面中渲染子路由对应的内容。
  1. import { Routes, Route, Link } from 'react-router-dom';
  2. function Users() {
  3.   return (
  4.    
  5.       <h2>Users</h2>
  6.       <Link to="1">User 1</Link>
  7.       <Link to="2">User 2</Link>
  8.       <Routes>
  9.         <Route path=":userId" element={<UserProfile />} />
  10.       </Routes>
  11.    
  12.   );
  13. }
  14. function UserProfile() {
  15.   const { userId } = useParams();
  16.   return <h3>User Profile for User ID: {userId}</h3>;
  17. }
复制代码
路由守卫
路由保护可以确保只有特定条件下(例如用户登录后)才能访问某些路由。可以通过创建一个高阶组件(HOC)来实现。
  1. function ProtectedRoute({ element, isAuthenticated }) {
  2.   return isAuthenticated ? element : <Navigate to="/login" />;
  3. }
  4. // 使用
  5. <Routes>
  6.   <Route path="/dashboard" element={<ProtectedRoute element={<Dashboard />} isAuthenticated={isLoggedIn} />} />
  7. </Routes>
复制代码
404 页面处理
可以使用通配符路由 * 来处理未匹配的路径,并显示 404 页面。
  1. [/code][size=4]5. 动态路由(match)[/size]
  2. 动态路由允许你在路径中使用参数,这样可以在 URL 中捕获动态值。例如,展示用户信息的页面。
  3. [code]
复制代码
类组件中

使用 URL 参数,可以使用 withRouter 高阶组件来获取路由的 props,包括 match、location 和 history 对象。
使用 withRouter 获取 URL 参数
  1. import React from 'react';
  2. import { withRouter } from 'react-router-dom';
  3. class UserProfile extends React.Component {
  4.   render() {
  5.     // 从 props 中获取 match 对象
  6.     const { match } = this.props;
  7.     const userId = match.params.userId; // 获取 URL 参数
  8.     return User ID: {userId};
  9.   }
  10. }
  11. // 使用 withRouter 将 UserProfile 包装起来
  12. export default withRouter(UserProfile);
复制代码
关键点

  • withRouter 是一个高阶组件,它将路由的相关信息作为 props 传递给被包装的组件。
  • match.params 中包含了 URL 中的动态参数,像这里的 userId。
确保在路由配置中使用 UserProfile 组件时,像这样设置路由:
  1. [/code][size=3]函数组件[/size]
  2. 直接使用 useParams 来获取 URL 参数:
  3. [code]import { useParams } from 'react-router-dom';
  4. function UserProfile() {
  5.   const { userId } = useParams();
  6.   return User ID: {userId};
  7. }
复制代码
6. 获取 修改 查询字符串(location)

https://example.com/users?userId=123&userName=Alice
1. 类组件获取查询字符串参数

在类组件中,我们通常使用 withRouter 高阶组件来访问路由相关的信息,包括查询字符串。
示例代码
  1. import React, { Component } from 'react';
  2. import { withRouter } from 'react-router-dom';
  3. class QueryParamsClassComponent extends Component {
  4.   render() {
  5.     const { location } = this.props; // 从 props 中获取 location 对象
  6.     const searchParams = new URLSearchParams(location.search); // 创建 URLSearchParams 对象
  7.     // 获取具体的参数
  8.     const userId = searchParams.get('userId'); // 获取 userId 参数
  9.     const name = searchParams.get('name'); // 获取 name 参数
  10.     // searchParams。set('userId', '456'); // 修改或添加 userId 参数
  11.     // searchParams.set('name', 'Alice'); // 修改或添加 name 参数
  12.     return (
  13.       
  14.         <h1>Query Parameters</h1>
  15.         <p>User ID: {userId}</p>
  16.         <p>Name: {name}</p>
  17.       
  18.     );
  19.   }
  20. }
  21. export default withRouter(QueryParamsClassComponent); // 使用 withRouter 包裹类组件
复制代码
代码解析

  • 引入 withRouter:首先需要引入 withRouter,它使得组件可以访问路由的 props。
  • 访问 location 对象:在 render 方法中,从 this.props 中获取 location 对象。
  • 使用 URLSearchParams

    • new URLSearchParams(location.search) 创建一个 URLSearchParams 对象,location.search 包含查询字符串(包括 ?)。
    • 通过 get 方法提取具体的参数值,例如 userId 和 name。

  • 渲染参数:在组件的 JSX 中渲染这些参数。
2. 函数组件获取查询字符串参数

在函数组件中,我们可以使用 useLocation Hook 来获取路由信息,包括查询字符串。
示例代码
  1. import React from 'react';
  2. import { useLocation } from 'react-router-dom';
  3. const QueryParamsFunctionComponent = () => {
  4.   const location = useLocation(); // 使用 useLocation 获取 location 对象
  5.   const searchParams = new URLSearchParams(location.search); // 创建 URLSearchParams 对象
  6.   // 获取具体的参数
  7.   const userId = searchParams.get('userId'); // 获取 userId 参数
  8.   const name = searchParams.get('name'); // 获取 name 参数
  9.   //searchParams.get('userId'); // 获取 userId 参数
  10.   //searchParams.get('name'); // 获取 name 参数
  11.   return (
  12.    
  13.       <h1>Query Parameters</h1>
  14.       <p>User ID: {userId}</p>
  15.       <p>Name: {name}</p>
  16.    
  17.   );
  18. };
  19. export default QueryParamsFunctionComponent; // 直接导出函数组件
复制代码
代码解析

  • 引入 useLocation:引入 useLocation Hook。
  • 调用 useLocation:在函数组件中调用 useLocation(),它返回当前路由的 location 对象。
  • 使用 URLSearchParams

    • new URLSearchParams(location.search) 创建一个 URLSearchParams 对象,用于解析查询字符串。
    • 使用 get 方法提取需要的参数值。

  • 渲染参数:在组件的 JSX 中渲染这些参数。
7、编程导航 history

1. history 对象的概念


  • 历史记录:history 对象是一个 JavaScript 对象,它表示浏览器的会话历史。每当用户访问一个新的 URL 时,浏览器会将该 URL 添加到历史记录中。
  • 导航:通过 history 对象,你可以编程式地导航到不同的页面,而不是仅仅依赖于用户点击链接。
2. history 对象的常用方法

history 对象提供了多种方法来处理导航和历史记录。以下是一些常用的方法:
push(path, [state])

  • 功能:在历史记录栈中添加一个新的条目,导航到指定的路径。
  • 参数

    • path:要导航到的路径。
    • state(可选):与新路径关联的状态对象,这个对象可以在目标页面通过 location.state 访问。

示例
  1. this.props.history.push('/home'); // 导航到 /home
  2. this.props.history.push('/profile', { from: 'home' }); // 导航到 /profile,并传递状态
复制代码
replace(path, [state])

  • 功能:替换当前的历史记录条目,导航到指定的路径,而不是添加一个新的条目。
  • 参数:同 push 方法。
示例
  1. this.props.history.replace('/login'); // 用 /login 替换当前的历史条目
复制代码
go(n)

  • 功能:根据历史记录栈中的位置导航。
  • 参数

    • n:要导航的相对位置(正数表示向前,负数表示向后)。

示例
  1. this.props.history.go(-1); // 返回到上一页
  2. this.props.history.go(2); // 前进两页
复制代码
goBack() 返回到上一页,等同于 go(-1)。
goForward() 前进到下一页,等同于 go(1)。
3. 在 React Router 中使用 history

在 React Router 中,history 对象通常是通过 withRouter 高阶组件或在函数组件中通过 useNavigate 和 useLocation Hook 访问的。
类组件使用 withRouter
  1. import React, { Component } from 'react';
  2. import { withRouter } from 'react-router-dom';
  3. class MyComponent extends Component {
  4.   handleNavigation = () => {
  5.     this.props.history.push('/home'); // 使用 history 导航
  6.   };
  7.   render() {
  8.     return <button onClick={this.handleNavigation}>Go to Home</button>;
  9.   }
  10. }
  11. export default withRouter(MyComponent); // 使用 withRouter 包裹组件
复制代码
函数组件使用 useNavigate
在 React Router v6 及以上版本中,推荐使用 useNavigate Hook 来获取 navigate 函数。
  1. import React from 'react';
  2. import { useNavigate } from 'react-router-dom';
  3. const MyFunctionComponent = () => {
  4.   const navigate = useNavigate();
  5.   const handleNavigation = () => {
  6.     navigate('/home'); // 使用 navigate 导航
  7.   };
  8.   return <button onClick={handleNavigation}>Go to Home</button>;
  9. };
  10. export default MyFunctionComponent;
复制代码
8、子组件的路由 Outlet
  1. // App.js
  2. import React from 'react';
  3. import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
  4. import UserProfile from './UserProfile';
  5. import UserSettings from './UserSettings';
  6. import UserActivity from './UserActivity';
  7. const App = () => {
  8.   return (
  9.     <Router>
  10.       <Routes>
  11.         <Route path="/users/*" element={<UserProfile />}>
  12.           <Route path="settings" element={<UserSettings />} />
  13.           <Route path="activity" element={<UserActivity />} />
  14.         </Route>
  15.       </Routes>
  16.     </Router>
  17.   );
  18. };
  19. export default App;
  20. // UserProfile.js
  21. import React from 'react';
  22. import { Link, Outlet } from 'react-router-dom';
  23. const UserProfile = () => {
  24.   return (
  25.    
  26.       <h1>User Profile</h1>
  27.       <nav>
  28.         <ul>
  29.           <li>
  30.             <Link to="settings">Settings</Link>
  31.           </li>
  32.           <li>
  33.             <Link to="activity">Activity</Link>
  34.           </li>
  35.         </ul>
  36.       </nav>
  37.       <Outlet /> {/* 渲染匹配的子路由 */}                // 路由
  38.    
  39.   );
  40. };
  41. export default UserProfile;
  42. // UserSettings.js
  43. import React from 'react';
  44. const UserSettings = () => {
  45.   return <h2>User Settings</h2>;
  46. };
  47. export default UserSettings;
  48. // UserActivity.js
  49. import React from 'react';
  50. const UserActivity = () => {
  51.   return <h2>User Activity</h2>;
  52. };
  53. export default UserActivity;
复制代码
7、redux 集中状态管理

Redux.createStore 是 Redux 的传统方式,用于创建 Redux store。
Redux.createStore


  • 导入 Redux:
  1. import { createStore } from 'redux';
复制代码

  • 定义初始状态:
  1. const initialState = {
  2.   todos: [],
  3. };
复制代码

  • 创建 Reducer:
Reducer 是一个纯函数,接受当前状态和 action,并返回新的状态。
  1. const todoReducer = (state = initialState, action) => {
  2.   switch (action.type) {
  3.     case 'ADD_TODO':
  4.       return { ...state, todos: [...state.todos, action.payload] };
  5.     default:
  6.       return state;
  7.   }
  8. };
复制代码

  • 创建 Store:
使用 createStore 创建 store,并传入 reducer。
  1. const store = createStore(todoReducer);
复制代码

  • 使用 Store:
可以使用 store.getState() 获取当前状态,使用 store.dispatch(action) 发送 action。
  1. store.dispatch({ type: 'ADD_TODO', payload: { text: 'Learn Redux' } });
  2. console.log(store.getState());
复制代码
Redux Toolkit

Redux Toolkit 是官方推荐的 Redux 工具集,它简化了 Redux 的使用,包含了一些开箱即用的工具和最佳实践。使用 Redux Toolkit 可以更容易地管理状态,减少模板代码。
1. 安装

首先,安装 Redux Toolkit 和 React-Redux:
  1. npm install @reduxjs/toolkit react-redux
复制代码
2. 创建 Slice

使用 createSlice 来定义 state、reducers 和 actions。这样可以简化代码结构。
  1. import { createSlice } from '@reduxjs/toolkit';
  2. const todosSlice = createSlice({
  3.   name: 'todos',
  4.   initialState: [], // 要存的state
  5.   // 使用 createSlice 创建 slice 时,定义的 reducer 函数会自动生成对应的 action creators。
  6.   reducers: {
  7.     addTodo: (state, action) => {        // state中包含所有 initialState 中的数据,
  8.       state.push(action.payload); // 使用 Immer 库来处理不可变状态
  9.     },
  10.     removeTodo: (state, action) => {
  11.       return state.filter(todo => todo.id !== action.payload);        // payload 包含了调用时传递的参数, 可以是对象
  12.     },
  13.   },
  14. });
  15. // 导出 action
  16. export const { addTodo, removeTodo } = todosSlice.actions;
  17. // 导出 reducer
  18. export default todosSlice.reducer;
复制代码
3. 配置 Store

使用 configureStore 来创建 store,它会自动添加 Redux DevTools 支持和中间件。
  1. import { configureStore } from '@reduxjs/toolkit';
  2. import todosReducer from './todosSlice';
  3. const store = configureStore({
  4.   reducer: {
  5.     todos: todosReducer,
  6.   },
  7. });
  8. export default store;
复制代码
4. 连接 React 和 Redux

在应用中使用 Provider 将 store 传递给组件树。
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { Provider } from 'react-redux';
  4. import store from './store';
  5. import App from './App';
  6. ReactDOM.render(
  7.   <Provider store={store}>
  8.    
  9.   </Provider>,
  10.   document.getElementById('root')
  11. );
复制代码
5. 使用 Redux State

在组件中使用 useSelector 和 useDispatch 来访问状态和发起 action。
  1. import React from 'react';
  2. import { useSelector, useDispatch } from 'react-redux';
  3. import { addTodo, removeTodo } from './todosSlice';
  4. const TodoList = () => {
  5.   const todos = useSelector(state => state.todos);
  6.   const dispatch = useDispatch();
  7.   const handleAddTodo = () => {
  8.     const text = prompt('Enter todo:');
  9.     const id = Date.now(); // 简单生成 ID
  10.     dispatch(addTodo({ id, text }));
  11.   };
  12.   const handleRemoveTodo = (id) => {
  13.     dispatch(removeTodo(id));
  14.   };
  15.   return (
  16.    
  17.       <h1>Todo List</h1>
  18.       <ul>
  19.         {todos.map(todo => (
  20.           <li key={todo.id}>
  21.             {todo.text}
  22.             <button onClick={() => handleRemoveTodo(todo.id)}>Remove</button>
  23.           </li>
  24.         ))}
  25.       </ul>
  26.       <button onClick={handleAddTodo}>Add Todo</button>
  27.    
  28.   );
  29. };
  30. export default TodoList;
复制代码
6. 处理异步操作

使用 createAsyncThunk 处理异步请求。
  1. import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
  2. // 异步操作示例
  3. export const fetchTodos = createAsyncThunk('todos/fetchTodos', async () => {
  4.   const response = await fetch('/api/todos');
  5.   return response.json();
  6. });
  7. const todosSlice = createSlice({
  8.   name: 'todos',
  9.   initialState: { items: [], status: 'idle' },
  10.   reducers: {},
  11.   extraReducers: (builder) => {
  12.     builder
  13.       .addCase(fetchTodos.fulfilled, (state, action) => {
  14.         state.items = action.payload;
  15.       });
  16.   },
  17. });
  18. // 导出 reducer
  19. export default todosSlice.reducer;
复制代码
8、hook

好的,我们来详细讲解一下 React Hooks,包括基本用法、常见的 Hooks 和具体的应用场景。
1、基本用法

React Hooks 是 React 16.8 引入的一种新特性,旨在让函数组件具备类组件的功能,尤其是状态管理和副作用处理。Hooks 的引入使得函数组件更加强大和灵活。
1. 使用 Hooks 的规则


  • 只能在函数组件或自定义 Hooks 中调用。 不可以在 普通 JavaScript 函数、类组件 或者 条件语句 中调用。
  • 调用顺序必须一致。 React 会根据调用的顺序来追踪每个 Hook 的状态。
2、常见的 Hooks

1. useState

用于在函数组件中添加状态。
  1. import React, { useState } from 'react';
  2. function Counter() {
  3.   const [count, setCount] = useState(0); // count 是状态,setCount 是更新状态的函数
  4.   return (
  5.    
  6.       <p>Count: {count}</p>
  7.       <button onClick={() => setCount(count + 1)}>Increment</button>
  8.    
  9.   );
  10. }
复制代码
2. useEffect

useEffect(()=> {}, 依赖项)
1.png

用于处理副作用,例如数据获取、订阅等。
  1. import React, { useState, useEffect } from 'react';
  2. function DataFetcher() {
  3.   const [data, setData] = useState(null);
  4.   useEffect(() => {
  5.     fetch('https://api.example.com/data')
  6.       .then(response => response.json())
  7.       .then(data => setData(data));
  8.     // 可选的清理函数
  9.     return () => {
  10.       // 例如取消订阅
  11.     };
  12.   }, []); // 依赖数组,空数组意味着仅在组件挂载时执行一次
  13.   return {data ? JSON.stringify(data) : 'Loading...'};
  14. }
复制代码
3. useContext

用于在组件之间共享状态,避免逐层传递 props。
  1. import React, { createContext, useContext } from 'react';
  2. const ThemeContext = createContext('light');
  3. function ThemedComponent() {
  4.   const theme = useContext(ThemeContext);
  5.   return Current theme: {theme};
  6. }
  7. function App() {
  8.   return (
  9.     <ThemeContext.Provider value="dark">
  10.       <ThemedComponent />
  11.     </ThemeContext.Provider>
  12.   );
  13. }
复制代码
4. useReducer

用于在复杂状态逻辑中管理状态,相比 useState 更加灵活。
  1. import React, { useReducer } from 'react';
  2. const initialState = { count: 0 };
  3. function reducer(state, action) {
  4.   switch (action.type) {
  5.     case 'increment':
  6.       return { count: state.count + 1 };
  7.     case 'decrement':
  8.       return { count: state.count - 1 };
  9.     default:
  10.       throw new Error();
  11.   }
  12. }
  13. function Counter() {
  14.   const [state, dispatch] = useReducer(reducer, initialState);
  15.   return (
  16.    
  17.       Count: {state.count}
  18.       <button onClick={() => dispatch({ type: 'increment' })}>+</button>
  19.       <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
  20.    
  21.   );
  22. }
复制代码
5. 自定义 Hooks

你可以创建自己的 Hooks,复用逻辑。
  1. import { useState, useEffect } from 'react';
  2. function useFetch(url) {
  3.   const [data, setData] = useState(null);
  4.   const [error, setError] = useState(null);
  5.   useEffect(() => {
  6.     fetch(url)
  7.       .then(response => response.json())
  8.       .then(setData)
  9.       .catch(setError);
  10.   }, [url]);
  11.   return { data, error };
  12. }
  13. // 使用自定义 Hook
  14. function DataFetcher({ url }) {
  15.   const { data, error } = useFetch(url);
  16.   if (error) return Error: {error.message};
  17.   return {data ? JSON.stringify(data) : 'Loading...'};
  18. }
复制代码
3、具体的应用场景


  • 数据获取: 使用 useEffect 和 useState 来从 API 获取数据。
  • 表单管理: 使用 useState 来管理输入框的状态,并处理提交。
  • 动画: 使用 useEffect 来设置动画的入场和离场。
  • 订阅: 在 useEffect 中添加订阅,返回一个清理函数以取消订阅。
  • 组合逻辑: 使用自定义 Hooks 来提取组件之间共享的逻辑。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册