ZhengXingchi / ZhengXingchi.github.io

Apache License 2.0
0 stars 0 forks source link

react #71

Open gone-with-the-wind opened 4 years ago

gone-with-the-wind commented 4 years ago

Suspense以及componentDidCatch

参考全面了解 React 新功能: Suspense 和 Hooks

React Suspense 尝鲜

gone-with-the-wind commented 4 years ago

react.suspense实现组件的懒加载

我们通过 webpack 或是 rollup 这样工具可以将项目多个 JavaScript 文件最终打包成为一个 bundle 文件。加载一个 js 文件速度要快于加载多个 JavaScript 文件。不过随着 bundle 的体积不断增大,最终造成首次加载时间过长,还有就是加载一些不必要的 javascript 文件。 所以我们想是否可以对 bundle 文件进行拆分来进行按需加载,就此需求 webpack 和 rollup 都给出自己解决方案,支持代码拆分,也就是 code splitting。

在react中我们可以通过lazy以及suspense来实现

const Foo = React.lazy(() => import('../components/Foo'));
const Bar = React.lazy(() => import('../components/Bar'));
export default class LazyPage extends Component {
    render() {
        return (
            <div>
                <Suspense fallback={<div>loading...</div>}>
                    <Bar/>
                    <Foo/>
                </Suspense>
            </div>
        )
    }
}

通过使用 Suspense 标签将要进行 lazy(懒加载)的组件进行包裹,然后在 fallback 函数中给出加载过程中处理方式,也就是加载过程中的行为。

gone-with-the-wind commented 4 years ago

异步加载数据

Suspense 异步加载数据截止到目前都是不稳定的版本,根据 React 16.x Roadmap,大概到2019年中期发布稳定版本,但是 React 官方提供了一个独立的包 react-cache,使用它结合 react@16.6.0 可以让我们提前感受一下 Suspense 异步加载数据。

components/Demo

import { unstable_createResource } from 'react-cache';

const getSomething = (something) => new Promise((resolve) => {
  setTimeout(() => {
    resolve(something);
  }, 1000);
})

const resource = unstable_createResource((id) => getSomething(id))

function Demo() {
  const data = resource.read(666)
  return (
    <div>{data}</div>
  );
}

App

const Demo =   import('../components/Demo')
export default class App extends Component {
    render() {
        return (
            <div>
                <Suspense fallback={<div>loading...</div>}>
                    <Demo/>
                </Suspense>
            </div>
        )
    }
}