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.


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

查看所有标签

猜你喜欢:

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

深度学习入门

深度学习入门

[ 日] 斋藤康毅 / 陆宇杰 / 人民邮电出版社 / 2018-7 / 59.00元

本书是深度学习真正意义上的入门书,深入浅出地剖析了深度学习的原理和相关技术。书中使用Python3,尽量不依赖外部库或工具,从基本的数学知识出发,带领读者从零创建一个经典的深度学习网络,使读者在此过程中逐步理解深度学习。书中不仅介绍了深度学习和神经网络的概念、特征等基础知识,对误差反向传播法、卷积神经网络等也有深入讲解,此外还介绍了深度学习相关的实用技巧,自动驾驶、图像生成、强化学习等方面的应用,......一起来看看 《深度学习入门》 这本书的介绍吧!

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

在线图片转Base64编码工具

MD5 加密
MD5 加密

MD5 加密工具

html转js在线工具
html转js在线工具

html转js在线工具