From 7d0945a5459dc2292a20bd674a7a4cc402b7b836 Mon Sep 17 00:00:00 2001 From: yujiang <287650464@qq.com> Date: Tue, 5 Mar 2024 10:24:14 +0800 Subject: [PATCH 1/9] =?UTF-8?q?[Issues:=20#I95SUW]=20=E6=B7=BB=E5=8A=A0rea?= =?UTF-8?q?ct-lifecycles-compat=E6=93=8D=E4=BD=9C=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 1224/react-lifecycles-compat.md | 130 ++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 1224/react-lifecycles-compat.md diff --git a/1224/react-lifecycles-compat.md b/1224/react-lifecycles-compat.md new file mode 100644 index 00000000..34a25e4a --- /dev/null +++ b/1224/react-lifecycles-compat.md @@ -0,0 +1,130 @@ +> 模板版本:v0.1.3 + +

+

react-lifecycles-compat

+

+

+ + License + +

+ + +> [!TIP] [Github 地址](https://github.com/reactjs/react-lifecycles-compat) + +## 安装与使用 + +进入到工程目录并输入以下命令: + +>[!TIP] # 处替换为 tgz 包的路径 + + + +#### **npm** + +```bash +npm install react-lifecycles-compat@3.0.4 +``` + +#### **yarn** + +```bash +yarn add react-lifecycles-compat@file@3.0.4 +``` + + + +下面的代码展示了这个库的基本使用场景: + +```js +import React from 'react'; +import { + Text, + View, + Button +} from 'react-native'; +import { polyfill } from 'react-lifecycles-compat'; +import { State } from 'react-native-gesture-handler'; +class ShowComponent extends React.Component { + render() { + return ( + + 新组件 + + ) + } +} +class ExampleComponent extends React.Component { + state = { + Text1: '未执行', + count1: 0, + Text2: '未执行', + visible: false + }; + static getDerivedStateFromProps = (nextProps, prevState) => { + // Normally this method would only work for React 16.3 and newer, + // But the polyfill will make it work for older versions also! + return { Text1: '已执行', count1: prevState.count1 + 1 } + } + + getSnapshotBeforeUpdate(prevProps, prevState) { + // Normally this method would only work for React 16.3 and newer, + // But the polyfill will make it work for older versions also! + return true + } + componentDidUpdate(prevProps, prevState, snapshot) { + if (snapshot) { + if (this.state.Text2 !== '已执行') { + this.setState({ + Text2: '已执行' + }) + } + + } + } + // render() and other methods ... + handleClick = () => { + this.setState({ visible: true }) + } + render() { + const { visible, Text1, Text2, count1 } = this.state + return ( + + {visible ? : {visible}} + getDerivedStateFromProps生命周期会在React初始化挂载和后续更新时调用render之前调用,返回一个对象来更新state,或者返回null就不更新任何内容 + getSnapshotBeforeUpdate生命周期会在React更新DOM之前时直接调用,使你的组件能够在DOM发生更改之前捕获一些信息 +