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

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

内容简介: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.


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

查看所有标签

猜你喜欢:

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

总开关

总开关

[美] 吴修铭 / 顾佳 / 中信出版社 / 2011-8 / 49.00元

当收音机经历从真空管收音机到半导体收音机,再到电晶体收音机的发展升级时,人们觉得自己的资讯来源美满得无可复加了。当约翰.洛吉.贝尔德发明了电视以后,在很长一段时间内,人们都认为电视就是他们所拥有的﹑也是所愿意拥有的最好的资讯媒介。 时至今日,互联网的震撼不亚于以往任何媒介,它给我们带来了最大的信息量,最便捷的自我表达,最迅速的沟通。互联网似乎比以往任何媒介都具有优越性。在互联网成为这个时代主......一起来看看 《总开关》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试