Skip to main content

6 posts tagged with "react"

View All Tags

React Components 生命周期

· 3 min read
Ordinary Magician | Half stack developer

在 React.Component 的子类中有个必须定义的 render() 函数。render() 方法是 class 组件中唯一必须实现的方法。当 render 被调用时,它会检查 this.props 和 this.state 的变化并返回以下类型之一:

  • React 元素。通常通过 JSX 创建。例如,<div /> 会被 React 渲染为 DOM 节点,<MyComponent /> 会被 React 渲染为自定义组件,无论是 <div /> 还是 <MyComponent /> 均为 React 元素。
  • 数组或 fragments。 使得 render 方法可以返回多个元素。
  • Portals。可以渲染子节点到不同的 DOM 子树中。
  • 字符串或数值类型。它们在 DOM 中会被渲染为文本节点
  • 布尔类型或 null。什么都不渲染。(主要用于支持返回 b && <Child /> 的模式,其中 b 为布尔类型。)

render() 函数应该为纯函数,这意味着在不修改组件 state 的情况下,每次调用时都返回相同的结果,并且它不会直接与浏览器交互。

React 异步渲染内容

· 2 min read
Ordinary Magician | Half stack developer

在React(typescript)中渲染需即时加载的元素。主要思路是使用useEffect Hook加载内容,而后使用useState Hook在加载完成时重新渲染界面。简短的代码描述如下:

interface AsyncCompomentProps {
func: () => Promise<JSX.Element>;
default?: JSX.Element;

function AsyncComponent(props: AsyncCompomentProps) {
const [loaded, setLoaded] = useState<JSX.Element>(null);
useEffect(() => {
props.func().then((result) => {
}, []);
return loaded ? loaded : props.default ?? <div>Loading...</div>;

func={async () => {
await new Promise((r) => setTimeout(r, 3000));
return <div>hi</div>;
default={<div>I'm loading...</div>}

Introducing React Query : Hooks for fetching

· 2 min read
Ordinary Magician | Half stack developer
  • What is React Query? it's a library for fetching data in React applications.

  • Why I need a data fetching library?

    1. Since React is a UI library, there is no specific pattern for data fetching.
    2. There are useEffect hooks for data fetching and useState hooks to maintain component state like loading, error or resulting data.
    3. If the data is needed throughout the app, we tend to use state management libraries. Although most of the state management libraries are good for working with client states, they are not great for working with asynchronus or server states. (server states are very different to client states)

React Hooks

· 4 min read
Ordinary Magician | Half stack developer

Hooks are a new addition in React 16.8. They let you "hook into" React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. In older React, it's hard to reuse stateful logic between components. The older React doesn't offer a way to "attach" reusable behavior to a component. With Hooks, you can extract stateful logic from a component so it can be tested independently and reused. Hooks allow you to reuse stateful logic without changing your component hierarchy. This makes it easy to share Hooks among many components or with the community.

There are nine of them: