Extract a `react-blessed` Component and Add the `useInterval` Hook

栏目: IT技术 · 发布时间: 5年前

内容简介:The above video is hosted onThis is the 4th post in a series where we will be creating a developer dashboard in the terminal using... ~20 more lessons to come ...

The above video is hosted on egghead.io .

This is the 4th post in a series where we will be creating a developer dashboard in the terminal using react-blessed and react-blessed-contrib . For more information about the series and to take a sneak peak at what we're building, go to the 1st post in the series for more context.

  1. Bootstrap a react-blessed Terminal Application
  2. Add ESLint Rules to a react-blessed Application
  3. Change text font with figlet inside a react-blessed Application
  4. Extract a react-blessed Component and Add the useInterval hook (this post)

... ~20 more lessons to come ...

NOTE: You can find the code for this project in GitHub and you watch the whole Build a Terminal Dashboard with React video series on egghead.io .

Large Dashboard.js File

The following is the current state of the dashboard.js file. Most of the functionality is all in one big file. The problem is that as we continue to build our dashboard this file will become hard to managed.

So, in this post we'll focus on moving out each section of our dashboard (which is just one at the moment) into their own React component.

import React from 'react';
import blessed from 'blessed';
import { render } from 'react-blessed';
import figlet from 'figlet';

const FONTS = [
  /* ... bunch of fonts ... */
];

const App = () => {
  const [fontIndex, setFontIndex] = React.useState(0);

  React.useEffect(() => {
    const timer = setTimeout(() => setFontIndex(fontIndex + 1), 1000);
    return () => clearTimeout(timer);
  }, [fontIndex]);

  const now = new Date();
  const date = now.toLocaleString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  });
  const time = figlet.textSync(
    now.toLocaleString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: true,
    }),
    {
      font: FONTS[fontIndex % FONTS.length],
    },
  );

  return (
    <box
      top="center"
      left="center"
      width="65%"
      height="65%"
      border={{ type: 'line' }}
      style={{
        border: { fg: 'blue' },
      }}
    >
      {`${date}
${time}`}
    </box>
  );
};

const screen = blessed.screen({
  autoPadding: true,
  smartCSR: true,
  title: 'Developer Dashboard',
});

screen.key(['escape', 'q', 'C-c'], () => process.exit(0));

render(<App />, screen);

Simplify Dashboard.js File

To simplify our dashboard.js file we'll copy most of the code and move it into a new file called Today.js . The remaining pieces are concerned with react-blessed and rendering the top level components. Currently, we only need to render the <Today /> component, but in subsequent posts we will add others.

import React from 'react';
import blessed from 'blessed';
import { render } from 'react-blessed';
import Today from './components/Today';

const App = () => {
  return <Today updateInterval={1000} />;
};

const screen = blessed.screen({
  autoPadding: true,
  smartCSR: true,
  title: 'Developer Dashboard',
});

screen.key(['escape', 'q', 'C-c'], () => process.exit(0));

render(<App />, screen);

New Today.js Component

The new Today.js component is code taken from the previous version of dashboard.js . The main difference is that we export the component to make it available for the dashboard to import.

import React from 'react';
import figlet from 'figlet';

const FONTS = [
  /* ... bunch of fonts ... */
];

export default function Today({ updateInterval = 1000 }) {
  const [fontIndex, setFontIndex] = React.useState(0);

  React.useEffect(() => {
    const timer = setTimeout(() => setFontIndex(fontIndex + 1), 1000);
    return () => clearTimeout(timer);
  }, [fontIndex]);

  const now = new Date();
  const date = now.toLocaleString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  });
  const time = figlet.textSync(
    now.toLocaleString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: true,
    }),
    {
      font: FONTS[fontIndex % FONTS.length],
    },
  );

  return (
    <box
      top="center"
      left="center"
      width="65%"
      height="65%"
      border={{ type: 'line' }}
      style={{
        border: { fg: 'blue' },
      }}
    >
      {`${date}
${time}`}
    </box>
  );
}

Replace useEffect/setTimeout with useInterval

In our next post we will start fetching data to populate or refresh our widgets, so we'll do a little preparation for that. Instead of using React.useEffect and window.setTimeout , let's move to an interval approach instead. We could try combining React.useEffect and window.setInterval , but there are some oddities that can arise when merging those ideas.

Dan Abramov goes into great detail explaining concerns of using React.useEffect and window.setInterval in a blog post titled Making setInterval Declarative with React Hooks . The gist is that if the code is rendered to frequently the window.setInterval could get cleared before it has a chance to trigger. So, we'll install a custom React hook called useInterval , written by Donavon West , that takes into consideration the issues brought up by Dan.

npm install @use-it/interval
import React from 'react';
import figlet from 'figlet';
import useInterval from '@use-it/interval';
const FONTS = [
  /* ... bunch of fonts ... */
];

export default function Today({ updateInterval = 1000 }) {
  const [fontIndex, setFontIndex] = React.useState(0);

  useInterval(() => {    setFontIndex(fontIndex + 1);  }, updateInterval);
  /* ... rest of code ... */

  return ( /* ... JSX ... */ );
}

Conclusion

Since we pulled out code from dashboard.js into Today.js , the code is a now bit more streamlined and setup for future enhancements.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

瞬间之美

瞬间之美

[美] Robert Hoekman, Jr. / 向怡宁 / 人民邮电出版社 / 2009-7 / 45.00元

本书特色: 本书通过重现用户面对Web应用时由始至终的完整情境,主要针对Web应用中几乎所有相关元素,例如Search、Screencast、Blog 、Wizard、 RSS、 Rate 、TagCloud 以及Form的布局、交互甚至客服等都提出了值得借鉴的解决方案。具体通过30多个故事轻松自然地带领读者领会设计者如何百分之百地用心传达以创造美好的用户体验。 本书适用于信息架构设计......一起来看看 《瞬间之美》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具