wdnmd

react16+项目练习

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

1.封装错误处理组件。

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

1
2
3
4
<ErrorBoundary fallbackRender={FullPageErrorFallback}>
{/* <ProjectListScreen/> */}
{ user? <Auth/> :<Unauth/>}
</ErrorBoundary>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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请求,主要是加上一些验证信息,响应处理,错误处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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 @   FreshChick  阅读(153)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示