React 笔记— Hooks

本文基于官方 v18.1.0 文档。

Introducing Hooks

They let you use state and other React features without writing a class.

Motivation

It’s hard to reuse stateful logic between components

现在可以通过自定义 Hook 提取封装带状态的逻辑。

Complex components become hard to understand

useEffect 可以把复杂逻辑分拆到多个小的函数中。

Classes confuse both people and machines

阅读更多

React 笔记—高级指引

本文基于官方 v18.1.0 文档。

Code-Splitting

Code Splitting

You need to keep an eye on the code you are including in your bundle so that you don’t accidentally make it so large that your app takes a long time to load.

Code-Splitting is a feature supported by bundlers like Webpack, Rollup and Browserify (via factor-bundle) which can create multiple bundles that can be dynamically loaded at runtime.

Code-splitting your app can help you “lazy-load” just the things that are currently needed by the user, which can dramatically improve the performance of your app.

阅读更多

React 笔记—核心概念

本文基于官方 v18.1.0 文档。

Introducing JSX

Why JSX?

React embraces the fact that rendering logic is inherently coupled with other UI logic:
how events are handled, how the state changes over time, and how the data is prepared for display.

Instead of artificially separating technologies by putting markup and logic in separate files,
React separates concerns with loosely coupled units called “components” that contain both.

这是当初 React 最吸引我的地方,不执著于将 UI 和逻辑分开。MVC 大行其道几十年后,Android 跟 iOS 也都在尝试返濮了。
在我实际工作经验中,进行视图子类化定制的出发点往往就是为了将 UI 和其逻辑写在一起。这个需求越靠近业务层就越强烈。

阅读更多

Webpack 打包 React 组件

之前 通过直接运行 babel 相关命令,把 jsx 语法做了预处理。但输出远远达不到 create-react-app 的水平。 Google 了一圈发现,原来可以通过 webpack 把 jsx 预处理、js 压缩、js 打包几个步骤一次性执行。

初始化 Webpack Config

安装 webpack:

1
npm i webpack webpack-cli
阅读更多

React + Jsx 多页面配置

  1. 多页面用不到 create-react-app,项目结构需要手动配置。
  2. Jsx 不能带到生产环境去,会导致每次加载 js 文件时都要做语法转换,所以需要用 babel 预处理。

项目根目录下,创建 package.json:

1
npm init -y

把 html 文件放在 src 目录下,js 文件放在 src/js 目录下。html 中引入对应的 js:

1
<script src="/js/index.js"></script>

不要加 type=”text/babel”,路径其实对应的是预处理后的、被转换的 js 文件。

https://reactjs.org/docs/add-react-to-a-website.html

阅读更多