当前位置:   article > 正文

react项目总结_react项目经验

react项目经验

本文章主要是源自实际项目开发项目的总结,一些思考是参考了看过的文章,做了一篇总结,demo是跑过的,可以放心食用。

目录

       一.组件通信

1.父组件向子组件通信

2.子组件向父组件通信

3.跨级组件通信

4.兄弟组件通信

5.无嵌套关系的组件通信

二、避免重复渲染

1.隔离独立渲染的子组件

2.与渲染无关的变量不用state来管理数据

3.批量更新state、合并state

4.class组件中使用shouldComponentUpdate

5.绑定事件尽量不使用箭头函数

三、代码优化

1.大量的props

2.不兼容的props

3.props经过处理变为state

4.使用枚举管理状态

5.自定义Hook

四、其他优化

1.使用React.Fragment减少额外标签

2.避免使用内联样式属性

3.优化条件渲染

五、懒加载

1.懒加载React组件、第三方依赖组件

2.不用React.lazy懒加载


一.组件通信

1.父组件向子组件通信

  • 向子组件传递props
  1. <ChildList list={this.state.list} />
  2. <ChildSettings {...this.state.options} />
  • 父组件调用子组件中的方法

1)函数组件:父组件useRef()创建一个ref,通过ref属性附加到子组件上,子组件用forwardRef来获取传递给它的ref,配合useImperativeHandle使用可以自定义暴露给父组件的方法

  1. // 父组件
  2. import { useRef } from "react";
  3. const childRef = useRef();
  4. useEffect(() => {
  5. childRef.current.childFunc();
  6. }, []);
  7. return (
  8. <div>
  9. <Child ref={childRef} />
  10. </div>
  11. );
  12. // 子组件
  13. import { forwardRef, useImperativeHandle } from "react";
  14. const Child = forwardRef((props, ref) => {
  15. useImperativeHandle(ref, () => ({
  16. childFunc() {
  17. return logChild();
  18. },
  19. }));
  20. const logChild = () => {
  21. console.log("---child-----");
  22. };
  23. return <div>child</div>;
  24. });
  25. export default Child;

2)class组件:子组件通过调用父组件的props方法,将子组件本身暴露出去,父组件可直接使用子组件内的方法,不想暴露给父组件的方法可以用static关键字定义静态方法

  1. // 父组件
  2. export default class Parent extends React.Component {
  3. onClick = () => {
  4. this.childRef.childFunc();
  5. };
  6. render() {
  7. return (
  8. <div>
  9. <Child
  10. onRef={(ref) => {
  11. this.childRef = ref;
  12. }}
  13. />
  14. <button onClick={this.onClick}>click</button>
  15. </div>
  16. );
  17. }
  18. }
  19. // 子组件
  20. class Child extends React.Component {
  21. componentDidMount() {
  22. this.props.onRef(this);
  23. }
  24. static myFunc = () => {
  25. console.log('本方法不暴露给父组件');
  26. };
  27. childFunc = () => {
  28. console.log("---child-----");
  29. };
  30. render() {
  31. return <div>child</div>;
  32. }
  33. }
  34. export default Child;

2.子组件向父组件通信

父组件向子组件传递props方法,子组件主动调用该方法,将需要的信息作为参数传递到父组件的作用域中

  1. // 父组件
  2. <ChildSelector
  3. value={this.state.selectedValue}
  4. onSelect={(selectedValue) => {
  5. this.setState({
  6. selectedValue
  7. })
  8. }}
  9. />
  10. // 子组件
  11. onSelect = (value) => {
  12. this.props.onSelect(value);
  13. }

3.跨级组件通信

使用Context共享组件树上能够全局访问的数据。注:Child1为Child的子组件

1)React.createContext(defaultValue)创建Context对象,订阅了Context对象的组件会从组件树中找到离自身最近的Provider中读取到当前的context,Context对象会返回Provider组件,允许Consumer消费组件订阅context的变化

  1. // context/AppContext.js
  2. import { createContext } from "react";
  3. export default createContext({
  4. name: "",
  5. changeName: () => {},
  6. });

2)函数组件:子组件使用useContext(),接收一个context对象,返回该context的当前值

  1. // 根组件
  2. import { useState } from "react";
  3. import Child from "./Child";
  4. import Context from "./context/AppContext";
  5. const Parent = () => {
  6. const [name, setName] = useState("defaultName");
  7. const changeName = (name) => {
  8. setName(name);
  9. };
  10. return (
  11. <Context.Provider value={{ name, changeName }}>
  12. <Child />
  13. </Context.Provider>
  14. );
  15. };
  16. export default Parent;
  17. // 子组件Child1
  18. import { useContext } from "react";
  19. import Context from "./context/AppContext";
  20. const Child1 = () => {
  21. const context = useContext(Context);
  22. return <div onClick={() => context.changeName("Child")}>{context.name}</div>;
  23. };
  24. export default Child1;

3)class组件:子组件contextType属性会被重新赋值为一个由 React.createContext() 创建的 Context 对象

  1. // 根组件
  2. import Child from "./Child";
  3. import Context from "./context/AppContext";
  4. export default class Parent extends React.Component {
  5. state = {
  6. name: "defaultName",
  7. };
  8. changeName = (name) => {
  9. this.setState({
  10. name,
  11. });
  12. };
  13. render() {
  14. return (
  15. <Context.Provider
  16. value={{ name: this.state.name, changeName: this.changeName }}
  17. >
  18. <Child />
  19. </Context.Provider>
  20. );
  21. }
  22. }
  23. // 子组件Child1
  24. import { Component } from "react";
  25. import Context from "./context/AppContext";
  26. class Child1 extends Component {
  27. static contextType = Context;
  28. render() {
  29. return (
  30. <div onClick={() => this.context.changeName("Child")}>
  31. {this.context.name}
  32. </div>
  33. // 16.x版本后可写成,不需要定义contextType
  34. <Context.Consumer>
  35. {({ name, changeName }) => {
  36. return <div onClick={() => changeName("Child")}>{name}</div>;
  37. }}
  38. </Context.Consumer>
  39. );
  40. }
  41. }
  42. export default Child1;

4.兄弟组件通信

利用useReducer和context实现,可模仿一个简单的redux,useReducer传入reducer和defaultState,返回当前state和dispatch,通过context传给各个子组件,让子组件共享state和修改state

  1. // types.js
  2. export const EXAMPLE_TEST = "EXAMPLE_TEST";
  3. // reducer.js
  4. import * as Types from "./types";
  5. export const defaultState = {
  6. count: 0,
  7. };
  8. export default (state, action) => {
  9. switch (action.type) {
  10. case Types.EXAMPLE_TEST:
  11. return {
  12. ...state,
  13. count: action.count,
  14. };
  15. default: {
  16. return state;
  17. }
  18. }
  19. };
  20. // action.js
  21. import * as Types from "./types";
  22. export const onChangeCount = (count) => ({
  23. type: Types.EXAMPLE_TEST,
  24. count: count + 1,
  25. });
  1. // 根组件
  2. import React, { useReducer } from "react";
  3. import Context from "./context";
  4. import reducer, { defaultState } from "./reducer";
  5. import Child from "./Child";
  6. import Child1 from "./Child1";
  7. function ReducerCom() {
  8. const [state, dispatch] = useReducer(reducer, defaultState);
  9. return (
  10. <Context.Provider value={{ state, dispatch }}>
  11. <Child />
  12. <Child1 />
  13. </Context.Provider>
  14. );
  15. }
  16. export default ReducerCom;
  17. // Child.js
  18. import React, { useEffect, useContext } from "react";
  19. import { onChangeCount } from "./action";
  20. import Context from "./context";
  21. const Child = () => {
  22. const context = useContext(Context);
  23. useEffect(() => {
  24. // 监听变化
  25. console.log("变化执行啦");
  26. }, [context.state.count]);
  27. return (
  28. <button
  29. onClick={() => context.dispatch(onChangeCount(context.state.count))}
  30. >
  31. 点击加 1
  32. </button>
  33. );
  34. };
  35. export default Child;
  36. // Child1.js
  37. import React, { useContext } from "react";
  38. import Context from "./context";
  39. const Child1 = () => {
  40. const context = useContext(Context);
  41. return (
  42. <div>
  43. <p>{context.state.count}</p>
  44. </div>
  45. );
  46. };
  47. export default Child1;

5.无嵌套关系的组件通信

  • 使用redux、mobx、flux等状态管理器
  • 使用发布-订阅模式
  1. // EventEmitter.js
  2. class EventEmitter {
  3. constructor() {
  4. this.subscribers = {};
  5. }
  6. on(type, fn) {
  7. if (!this.subscribers[type]) {
  8. this.subscribers[type] = [];
  9. }
  10. this.subscribers[type].push(fn);
  11. }
  12. off(type, fn) {
  13. let listeners = this.subscribers[type];
  14. if (!listeners || !listeners.length) return;
  15. this.subscribers[type] = listeners.filter((v) => v !== fn);
  16. }
  17. emit(type, ...args) {
  18. let listeners = this.subscribers[type];
  19. if (!listeners || !listeners.length) return;
  20. listeners.forEach((fn) => fn(...args));
  21. }
  22. }
  23. export default new EventEmitter();
  1. // 组件1
  2. const Child = () => {
  3. const [name, setName] = useState("defaultName");
  4. useEffect(() => {
  5. EventEmitter.on("changeName", (name) => {
  6. setName(name);
  7. });
  8. return EventEmitter.off();
  9. }, []);
  10. return <div>{name}</div>;
  11. };
  12. // 组件2
  13. const Child1 = () => {
  14. const changeChildName = () => {
  15. EventEmitter.emit("changeName", "change name from child2");
  16. };
  17. return <button onClick={changeChildName}>click</button>;
  18. };

二、避免重复渲染

1.隔离独立渲染的子组件

用React.memo隔离组件形成独立的渲染单元,避免父组件重新渲染造成子组件也重新渲染,可以用于不依赖于父组件状态渲染的子组件,函数组件和class也可以用useMemo和pureComponent实现。

export default React.memo(Child);

1)函数组件:useMemo的第二个参数是依赖项数组,某个依赖项改变时才会重新渲染子组件。

  1. {useMemo(
  2. () => (
  3. <Child />
  4. ),
  5. []
  6. )}

2)class组件:用React.pureComponent

export default class Child extends React.PureComponent {}

2.与渲染无关的变量不用state来管理数据

触发this.setState或者useState,只要state改变就会触发渲染,与在render中是否引用无关,可以直接把数据绑定在this上,或者使用useRef做数据缓存。

1)函数组件

  1. const App = ({name}) => {
  2. const nameRef = useRef('defaultName');
  3. useEffect(() => {
  4. nameRef.current = name;
  5. })
  6. return <div>hello world!</div>;
  7. }

2)class组件

  1. class App extends React.Component{
  2. name = 'defaultName';
  3. componentDidMount() {
  4. this.name = this.props.name;
  5. }
  6. render () {
  7. return <div>hello world!</div>;
  8. }
  9. }

3.批量更新state、合并state

class组件如果在一个函数中setState了三次,会触发三次setState,但是不会渲染三次,因为react会合并成一次做批量更新,但是在异步函数中会多次渲染,批量更新失效。

demo如下:

  1. const Parent = () => {
  2. const [a, setA] = useState(0);
  3. const [b, setB] = useState(0);
  4. const [c, setC] = useState(0);
  5. const handleClick = () => {
  6. setA(a + 1);
  7. setB(b + 1);
  8. setC(c + 1);
  9. };
  10. console.log("----render----");
  11. return (
  12. <div>
  13. {a}---{b}---{c}
  14. <button onClick={handleClick}>click</button>
  15. </div>
  16. );
  17. };
  18. export default Parent;

效果如下:点击三次,才会render三次

如果是异步的更改state

  1. const handleClick = () => {
  2. setTimeout(() => {
  3. setA(a + 1);
  4. setB(b + 1);
  5. setC(c + 1);
  6. }, 0);
  7. };

效果如下:点击一次,就会render三次,说明没有合并更新

解决方案:

1)手动批量更新可以用react-dom中的unstable_batchedUpdates,三次更新就会合并成一次

  1. import { unstable_batchedUpdates } from 'react-dom';
  2. const handleClick = () => {
  3. setTimeout(() => {
  4. unstable_batchedUpdates(() => {
  5. setA(a + 1);
  6. setB(b + 1);
  7. setC(c + 1);
  8. });
  9. }, 0);
  10. };

2)合并state:用一个setState改变多个state,或者一个useState保存多个state

4.class组件中使用shouldComponentUpdate

使用shouldComponentUpdate控制组件是否需要重新渲染

  1. shouldComponentUpdate(nextProps, nextState) {
  2. if(nextState.id != this.state.id ) {
  3. return true;
  4. }
  5. return false;
  6. }

5.绑定事件尽量不使用箭头函数

使用箭头函数每次渲染都会创建一个新的时间处理器,子组件每次都会被渲染。

1)函数组件:子组件使用React.memo配合父组件用useCallback包裹props方法,实现父组件渲染不影响子组件的渲染

  1. <Child onClick={handleClick} />
  2. // 如果用箭头函数绑定事件父组件还是会影响子组件的渲染
  3. <Child onClick={(value) => handleClick(value)} />
  4. const handleClick = useCallback((value) => {
  5. console.log(value);
  6. }, []);

2)class组件:不用箭头函数,子组件用React.memo包裹即可

三、代码优化

1.大量的props

        如果需要将大量的props传递到一个组件中,那么可以思考以下几点:

1)该组件是否做了多件事,一个组件应该只做一件事,将该组件拆分成多个小组件是否会更合理;

2)组件是否可以被合成,如果组件中有很多不相干的逻辑,就可以考虑拆分再重新组合;

3)是否传递了很多配置有关的props,比如带分页配置的表格组件,可以将多个配置的props合成一个options,可以更好的控制组件选项,也更规范。

2.不兼容的props

        避免组件之间传递不兼容的props,例如有一个<Input/>组件功能是把输入的小写英文都转变成大写,过了一段时间,想将它用于电话号码的处理,虽然都是用的input元素,但是明显电话号码的处理用不上之前的功能,并且毫无关联,这时候也可以分割组件明确职责,如果有共享的逻辑可以放到hooks中

3.props经过处理变为state

        一般常规做法是,子组件内创建一个state,当props的值改变时再改变state,但是如果只是基于props通过计算得到新的state可以用useMemo来代替useState。

  1. const Child = ({ count }) => {
  2. const formatCount = (value) => {
  3. return value + 10;
  4. };
  5. const formattedCount = useMemo(() => {
  6. return formatCount(count);
  7. }, [count]);
  8. //const [formattedCount, setFormattedCount] = useState(count);
  9. //useEffect(() => {
  10. // setFormattedCount(formatCount(count));
  11. //}, [count]);
  12. return <div>{formattedCount}</div>;
  13. };
  14. export default Child;

4.使用枚举管理状态

在编写组件时,很容易用很多个布尔值来表示组件当前的状态,比如isLoading、isFinished等等,虽然技术可行,但是很难推断组件当前处于什么状态,不容易维护,可以用一个枚举的状态来表示。

  1. function Component() {
  2. const [isLoading, setIsLoading] = useState(false)
  3. const [isFinished, setIsFinished] = useState(false)
  4. const [hasError, setHasError] = useState(false)
  5. const fetchSomething = () => {
  6. setIsLoading(true)
  7. fetch(url)
  8. .then(() => {
  9. setIsLoading(false)
  10. setIsFinished(true)
  11. })
  12. .catch(() => {
  13. setHasError(true)
  14. })
  15. }
  16. if (isLoading) return <Loader />
  17. if (hasError) return <Error />
  18. if (isFinished) return <Success />
  19. return <button onClick={fetchSomething} />
  20. }
  21. // 改造后
  22. function Component() {
  23. const [status, setStatus] = useState('loading')
  24. const fetchSomething = () => {
  25. setStatus('loading')
  26. fetch(url)
  27. .then(() => {
  28. setStatus('finished')
  29. })
  30. .catch(() => {
  31. setStatus('error')
  32. })
  33. }
  34. if (status === 'loading') return <Loading />
  35. if (status === 'error') return <Error />
  36. if (status === 'finished') return <Success />
  37. return <button onClick={fetchSomething} />
  38. }

5.自定义Hook

        组件具有相似逻辑、某个状态具有自己的复杂逻辑或者和生命周期有关的函数封装可以考虑自定义Hook,也可以使用封装好的Hook库,比如Umi Hooks--https://hooks.umijs.org/zh-CN/hooks/async

1)场景一:通用查询表格

        没有用自定义Hook提取可重用函数之前,每个页面的查询表格组件都要维护自己的loading/list/pageNo等状态,每个组件的逻辑都是默认请求列表,在请求列表前loading置为true,请求完毕置为false,设置list的数据,设置分页器,点击查询再根据查询条件请求列表,用自定义Hook可以将这些重复的逻辑封装起来,返回这些通用的state,减少重复的代码,让这些状态统一管理起来,比如默认分页数可以统一在一个地方控制。
  1. const [list, setList] = useState([]);
  2. const [loading, setLoading] = useState(false);
  3. const [paginator, setPaginator] = useState({
  4. page: 1,
  5. pageSize: 20,
  6. });
  7. const fetchList = (fetchStatus) => {
  8. setLoading(true);
  9. getList({
  10. pageSize: paginator.pageSize,
  11. pageNo: paginator.page,
  12. name,
  13. }).then((res) => {
  14. setList(res.data);
  15. setLoading(false);
  16. }).catch(() => {
  17. setLoading(false);
  18. });
  19. };
  20. const handlePageSelect = (page, pageSize) => {
  21. setPaginator({ ...paginator, page, pageSize });
  22. };
  23. useEffect(() => {
  24. fetchList();
  25. }, [paginator.page, paginator.pageSize]);
  26. <Table rowMax={list && list.length} loading={loading} data={list} column={columns} />
  27. <Pagination
  28. prev
  29. next
  30. first
  31. last
  32. recordCount={total}
  33. pageSize={paginator.pageSize}
  34. activePage={paginator.page}
  35. onSelect={handlePageSelect}
  36. />

自定义组件 useTable.js

输入:查询列表的接口、【除了分页器之外的参数】、【处理列表数据的函数】、【请求接口完毕的回调】

输出:list、loading、getData函数、分页的配置项

  1. import { useState, useEffect } from 'react';
  2. const useTable = (getListData, extraParam = {}, handleData, callback) => {
  3. const [paginator, setPaginator] = useState({
  4. recordCount: 0,
  5. pageSize: 20,
  6. pageNo: 1,
  7. });
  8. const [list, setList] = useState([]);
  9. const [loading, setLoading] = useState(false);
  10. useEffect(() => {
  11. getData();
  12. }, [paginator.pageNo, paginator.pageSize]);
  13. const onSelect = (pageNo, pageSize) => {
  14. if (!isNaN(pageNo)) {
  15. const paginator = { ...paginator, pageSize, pageNo };
  16. setPaginator(paginator);
  17. }
  18. };
  19. // 调用接口,获取数据
  20. const getData = (pageNoParam, newParam) => {
  21. // 搜索条件改变查询的时候,当前页数重置为1
  22. const pageNo = !isNaN(pageNoParam) ? pageNoParam : paginator.pageNo;
  23. const paginatorExtra = { pageNo, pageSize: paginator.pageSize };
  24. setLoading(true);
  25. const params = newParam || extraParam;
  26. getListData &&
  27. getListData({ ...params, ...paginatorExtra })
  28. .then((res = { data: [] }) => {
  29. const data = res.data;
  30. const recordCount = res.total || res.count;
  31. let list = [];
  32. if (handleData) {
  33. list = handleData(data);
  34. } else {
  35. list = data.map((item) => {
  36. // 默认以id为key
  37. return { key: item.id, ...item };
  38. });
  39. }
  40. // 因为使用这个hook的地方可以手动调用getData,所以分页器在这里赋值
  41. setPaginator({ ...paginatorExtra, recordCount });
  42. setList(list);
  43. setLoading(false);
  44. callback && callback(list);
  45. })
  46. .catch((err) => {
  47. setLoading(false);
  48. });
  49. };
  50. return {
  51. list,
  52. loading,
  53. getData,
  54. tableProps: {
  55. prev: true,
  56. next: true,
  57. first: true,
  58. last: true,
  59. recordCount: paginator.recordCount,
  60. pageSize: paginator.pageSize,
  61. activePage: paginator.pageNo,
  62. pageNo: paginator.pageNo,
  63. onSelect,
  64. },
  65. };
  66. };
  67. export default useTable;

使用useTable()

  1. const { list, tableProps, loading, getData } = useTable(
  2. getList,
  3. { teamId, productName, status },
  4. (data) => {
  5. return data.map((item) => {
  6. return { ...item, id: item.uuid };
  7. });
  8. }
  9. );
  10. <Button type="primary" onClick={() => getData(1)}>查询</Button>
  11. <Table border rowMax={list.length} data={list} loading={loading} column={columns} />
  12. <Pagination {...tableProps} />

2)场景二:封装useInterval代替setInterval

为什么不直接使用setInterval?

        如下面的例子,在组件加载时定义一个定时器,卸载组件时也清空定时器,但是useEffect只会执行一次,setInterval中拿到的始终是第一次渲染时拿到的count为1,所以界面上始终上显示的是2。

        为了解决这个问题,把useEffect的第二个参数改成[count],这样就会每次拿到最新的count,但是每次count更改,定时器就会不停的新增和移除。

  1. funtion Counter() {
  2. const [count, setCount] = useState(1);
  3. useEffect(() => {
  4. const id = setInterval(() => {
  5. console.log(count); // 此时的count始终是1
  6. setCount(count + 1);
  7. }, 1000);
  8. return () => clearInterval(id);
  9. }, []);
  10. return <div>{count}</div>;
  11. };

解决办法1:函数式更新,useState 中的set方法可接收函数,该函数将接收之前的state,返回一个更新后的值。这样定时器每次拿到的是最新的值。

setCount((count) => count + 1);

解决办法2:用useRef将定时器函数提取出来,每次定时器触发的时候,都能获取到最新的count。

  1. const myRef = useRef(null);
  2. myRef.current = () => {
  3. setCount(count + 1);
  4. };
  5. useEffect(() => {
  6. const id = setInterval(() => {
  7. myRef.current();
  8. }, 1000);
  9. return () => clearInterval(id);
  10. }, []);

定义useInterval.js

  1. import { useEffect, useRef } from 'react';
  2. const useInterval = (callback, delay) => {
  3. const savedCallback = useRef();
  4. useEffect(() => {
  5. savedCallback.current = callback;
  6. }, [callback);
  7. useEffect(() => {
  8. let id;
  9. function tick() {
  10. savedCallback.current(() => {
  11. clearInterval(id);
  12. });
  13. }
  14. if (!isNaN(delay)) {
  15. id = setInterval(tick, delay);
  16. return () => clearInterval(id);
  17. }
  18. }, [delay]);
  19. };
  20. export default useInterval;

使用useInterval.js

  1. useInterval((clear) => {
  2. setCount(count + 1);
  3. }, 1000);

四、其他优化

1.使用React.Fragment减少额外标签

        每个组件都必须要唯一一个父标签,如果该标签只是为了当父标签,没有其他额外的用途,则可以用片段fragment包裹子元素,节省渲染器渲染额外的元素的工作量。

2.避免使用内联样式属性

        添加的内联样式是js对象不是真正的样式,需要花费更多的时间转换为等效的css样式属性,才会应用样式。

3.优化条件渲染

        安装和卸载 React 组件是昂贵的操作,所以用条件渲染减少安装和卸载组件。执行不同的if else语句切换渲染的组件,没有更改的部分不需要用条件控制,不必要每次改变state的时候都卸载并重新安装

五、懒加载

1.懒加载React组件、第三方依赖组件

    React16.6版本中,新增了React.lazy函数,可以动态加载React组件,配合webpack的code splitting,当用import()时,webpack监测到这个语法会自动进行代码分割,只有当组件被加载,对应的资源才会导入;Suspense组件可以指定在js加载完成之前的loading。适合路由懒加载、Tab切换、单个资源很大、第三方依赖组件很大的场景。

  1. import React, { Suspense, useState } from "react";
  2. const App = () => {
  3. const [showChild, setShowChild] = useState(false);
  4. const Child = React.lazy(() => import("./Child"));
  5. return (
  6. <div>
  7. <button
  8. onClick={() => {
  9. setTimeout(() => {
  10. setShowChild(true);
  11. }, 2000);
  12. }}
  13. >
  14. click
  15. </button>
  16. {showChild && (
  17. <Suspense fallback={<div>loading...</div>}>
  18. <Child />
  19. </Suspense>
  20. )}
  21. </div>
  22. );
  23. };

效果:2s后加载2.chunk.js

我们也可以指定这个js的名字

const Child = React.lazy(() => import(/* webpackChunkName: "child" */"./Child"));

因为网络问题或者组件内部错误导致资源加载失败时,可能会导致页面白屏,可以用Error Boundaries组件来优雅降级。

  1. class ErrorBoundary extends React.Component {
  2. state = { hasError: false };
  3. static getDerivedStateFromError(error) {
  4. return { hasError: true };
  5. }
  6. componentDidCatch(error, errorInfo) {
  7. console.log(error, errorInfo);
  8. }
  9. render() {
  10. if (this.state.hasError) {
  11. return <p>资源加载失败,请稍后重试</p>;
  12. }
  13. return this.props.children;
  14. }
  15. }
  16. // App组件
  17. {showChild && (
  18. <ErrorBoundary>
  19. <Suspense fallback={<div>loading...</div>}>
  20. <Child />
  21. </Suspense>
  22. </ErrorBoundary>
  23. )}

2.不用React.lazy懒加载

  1. import React, { useState, Component } from "react";
  2. // 异步按需加载component
  3. const asyncComponent = (getComponent) => {
  4. return class AsyncComponent extends Component {
  5. static Component = null;
  6. state = { Component: AsyncComponent.Component };
  7. componentDidMount() {
  8. if (!this.state.Component) {
  9. getComponent().then(({ default: Component }) => {
  10. AsyncComponent.Component = Component;
  11. this.setState({ Component });
  12. });
  13. }
  14. }
  15. render() {
  16. const { Component } = this.state;
  17. if (Component) {
  18. return <Component {...this.props} />;
  19. }
  20. return <div>loading...</div>;
  21. }
  22. };
  23. };
  24. const App = () => {
  25. const [showChild, setShowChild] = useState(false);
  26. const Child = asyncComponent(() =>
  27. import(/* webpackChunkName: "child" */ "./Child")
  28. );
  29. return (
  30. <div>
  31. <button
  32. onClick={() => {
  33. setTimeout(() => {
  34. setShowChild(true);
  35. }, 2000);
  36. }}
  37. >
  38. click
  39. </button>
  40. {showChild && <Child />}
  41. </div>
  42. );
  43. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/42549
推荐阅读