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

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

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


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

查看所有标签

猜你喜欢:

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

An Introduction to Probability Theory and Its Applications

An Introduction to Probability Theory and Its Applications

William Feller / Wiley / 1991-1-1 / USD 120.00

Major changes in this edition include the substitution of probabilistic arguments for combinatorial artifices, and the addition of new sections on branching processes, Markov chains, and the De Moivre......一起来看看 《An Introduction to Probability Theory and Its Applications》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器