React

cloud setups

组件的写法

function

function Hello({ ame }: Props) {
    return (
        
Hello, {name}
); } export default Hello;

class

class Hello extends React.Component {
    render() {
        const { name } = this.props;
        return (
            
Hello, {name}
); } }

函数式组件和类组件的不同

React Hooks由于是函数式组件,在异步操作或者使用useCallBack、useEffect、useMemo等API时会形成闭包。

Hooks

1. useState

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <> Count: {count}    
  );
}

2. useReducer

reducer: (state, action) => newState
适用情况:

const initialState = { count: 0 };

type ACTIONTYPE =
  | { type: "increment"; payload: number }
  | { type: "decrement"; payload: string };

function reducer(state: typeof initialState, action: ACTIONTYPE) {
  switch (action.type) {
    case "increment":
      return { count: state.count + action.payload };
    case "decrement":
      return { count: state.count - Number(action.payload) };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      
      
    
  );
}
惰性初始化

init 函数作为 useReducer 的第三个参数传入,这样初始 state 将被设置为 init(initialArg)

import * as React from "react";
import { useReducer } from "react";

const initialCount = 0;

type ACTIONTYPE =
  | { type: "increment"; payload: number }
  | { type: "decrement"; payload: string }
  | { type: "reset"; payload: number };

function init(initialCount: number) {
  return { count: initialCount };
}

function reducer(state: {count: number}, action: ACTIONTYPE) {
  switch (action.type) {
    case "reset":
      return init(action.payload);
    case "increment":
      return { count: state.count + action.payload };
    case "decrement":
      return { count: state.count - Number(action.payload) };
    default:
      throw new Error();
  }
}

export function Counter() {
  const [state, dispatch] = useReducer(reducer, initialCount, init);
  return (
    <>
      Count: {state.count}
      
      
      
    
  );
}

3. useEffect

function DelayedEffect(props: { timerMs: number }) {
  const { timerMs } = props;

  useEffect(() => {
    setTimeout(() => {
      /* do stuff */
    }, timerMs);
  }, [timerMs]);
  // better; use the void keyword to make sure you return undefined
  return null;
}

4. useRef

const ref1 = useRef(null!);
const ref2 = useRef(null);
const ref3 = useRef(null);

useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内保持不变。

function TextInputWithFocusButton() {
  // initialise with null, but tell TypeScript we are looking for an HTMLInputElement
  const inputEl = React.useRef(null);
  const onButtonClick = () => {
    // strict null checks need us to check if inputEl and current exist.
    // but once current exists, it is of type HTMLInputElement, thus it
    // has the method focus! ✅
    if (inputEl && inputEl.current) {
      inputEl.current.focus();
    }
  };
  return (
    <>
      {/* in addition, inputEl only can be used with input elements. Yay! */}
      
      
    
  );
}

Custom Hooks

export function useLoading() {
  const [isLoading, setState] = React.useState(false);
  const load = (aPromise: Promise) => {
    setState(true);
    return aPromise.finally(() => setState(false));
  };
  return [isLoading, load] as const; // infers [boolean, typeof load] instead of (boolean | typeof load)[]
}

也可以写成:

export function useLoading() {
  const [isLoading, setState] = React.useState(false);
  const load = (aPromise: Promise) => {
    setState(true);
    return aPromise.finally(() => setState(false));
  };
  return [isLoading, load] as [
    boolean,
    (aPromise: Promise) => Promise
  ];
}

Enum 类型
尽量避免使用枚举类型,可以用以下代替:

export declare type Position = "left" | "right" | "top" | "bottom";

React+TypeScript Cheatsheets
你真的了解React Hooks吗?

你可能感兴趣的:(React)