react 组件化
React 界面完全由数据驱动
官网对组件的解释:Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen. 概念上类似于 JavaScript 函数。它接受任意的入参(即 “props”),并返回用于描述页面展示内容的 React 元素。
简单理解用公式表示:UI = f(data), data包括(state, props)。不直接操纵dom元素,而是修改数据,由数据去驱动react来修改界面。
React 中一切都是组件
官网对react element, react components, browser Dom的关系的几句解释:
- An element describes what you want to see on the screen.
- Unlike browser DOM elements, React elements are plain objects, and are cheap to create. React DOM takes care of updating the DOM to match the React elements.
- Elements are what components are “made of”.
简单理解:用户的界面就是由元素组成的组件 。(上面提到,组件从概念上是js函数, 而在js中一切皆对象,函数也是一个对象)
react 组件除了可以通过嵌套复用组成各种用户界面。还可以用来实现副效应(side effect)。比如不渲染任何页面,只获取数据资源。(react 新版本中函数组件也可以通过hook实现副作用)
备注: 钩子(hook)就是 React 函数组件的副效应解决方案,用来为函数组件引入副效应。
React 为许多常见的操作(side effect),都提供了专用的hook。useState保存状态, useContext()保存上下文, useRef()保存引用, 而 useEffect()是通用的副效应钩子 。找不到对应的钩子时,就可以用它。其实,从名字也可以看出来,它跟副效应(side effect)直接相关。
React 组件用props实现单向数据流
官网对props和组件解释:
- When React sees an element representing a user-defined component, it passes JSX attributes and children to this component as a single object. We call this object “props”.
- All React components must act like pure functions with respect to their props.
简单概括:props: 组件上的属性,以及children 组成的对象。注意,props是只读的。react组件通过props, 实现自上至下的单向数据流。
class组件 vs function组件
推荐Dan Abramov 大佬写的how-are-function-components-different-from-classes
不管是以前的class组件,还是现在用hook的函数组件,本质上都是js函数,接受数据props入参,返回描述页面的元素或处理side effect。
hook函数组件肯定是react未来的方向。跟jsx写法配合,相关业务逻辑,状态的复用更方便,组件的颗粒度更小,可读性和后期维护都更好。
下面图简单梳理了一下两者区别。