wdnmd

react16+项目练习

用到了react17,跟ts,功能不难,主要采取了hooks来写,对一些常用操作进行了封装,基础逻辑都不难,重点都在初始化,一些请求东西的封装。

1.封装错误处理组件。

 getDerivedStateFromError:state中标记这个错误,如果子组件渲染报错,父组件中会触发getDerivedStateFromError,并通过返回对象修改错误标记,最后父组件根据这个错误标记,决定渲染哪个页面

      <ErrorBoundary fallbackRender={FullPageErrorFallback}>
      {/* <ProjectListScreen/> */}
      { user? <Auth/> :<Unauth/>}
      </ErrorBoundary>
import React, { ReactNode } from 'react'

type FallbackRender = (props: {error: Error| null}) => React.ReactElement
export class ErrorBoundary extends React.Component<{children: ReactNode,fallbackRender: FallbackRender},{error: Error|null}>{
    state = {
        error: null
    }
    static getDerivedStateFromError(error: Error){
        return {error}
    }
    render(){
        const {error} = this.state
        const {fallbackRender, children} = this.props
        if(error){
            return fallbackRender({error})
        }
        return children
    }
}

 2.封装http请求,主要是加上一些验证信息,响应处理,错误处理。

import qs from "qs";
import * as auth from "auth-provider";
import { useAuth } from "context/auth-context";
const apiUrl = process.env.REACT_APP_API_URL;

interface Config extends RequestInit {
  token?: string;
  data?: object;
}

export const http = async (
  endpoint: string,
  { data, token, headers, ...customConfig }: Config = {}
) => {
  const config = {
    method: "GET",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": data ? "application/json" : "",
    },
    ...customConfig,
  };
  if (config.method.toUpperCase() === "GET") {
    endpoint += `?${qs.stringify(data)}`;
  } else {
    config.body = JSON.stringify(data || {});
  }
  return window
    .fetch(`${apiUrl}/${endpoint}`, config)
    .then(async (response) => {
      if (response.status === 401) {
        await auth.logout();
        window.location.reload();
        return Promise.reject({ message: "请重新登陆" });
      }
      const data = await response.json();
      if (response.ok) {
        return data;
      } else {
        return Promise.reject(data);
      }
    });
};

export const useHttp = () => {
  const { user } = useAuth();
  return (...[endpoint, config]: Parameters<typeof http>) =>
    http(endpoint, { ...config, token: user?.token });
};

 3.

posted @ 2022-02-15 11:58  FreshChick  阅读(144)  评论(0编辑  收藏  举报