博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
react hooks使用_如何使用React Hooks创建响应式固定数据表
阅读量:2524 次
发布时间:2019-05-11

本文共 11005 字,大约阅读时间需要 36 分钟。

react hooks使用

One of my projects uses a library called (FDT2), and it’s great for efficiently rendering tons of rows of data.

我的一个项目使用了一个名为 (FDT2)的库,它对于有效地呈现大量数据行非常有用。

Their documentation that resizes based on the browser’s width and height.

他们的文档 ,该根据浏览器的宽度和高度进行调整。

I thought it’d be cool to share this example using React Hooks.

我认为使用React Hooks分享这个例子很酷。

什么是React Hooks? (What are React Hooks?)

They’re functions that give you React features like state and lifecycle hooks without ES6 classes.

它们是为您提供React功能的功能,例如没有ES6类的状态和生命周期挂钩。

Some benefits are

一些好处是

  • isolating stateful logic, making it easier to test

    隔离状态逻辑,使其更易于测试
  • sharing stateful logic without render props or higher-order components

    共享状态逻辑而无需渲染道具或高阶组件
  • separating your app’s concerns based on logic, not lifecycle hooks

    根据逻辑而非生命周期挂钩来分离应用程序的关注点
  • avoiding ES6 classes, because they’re quirky, not actually classes, and trip up even experienced JavaScript developers

    避免使用ES6类,因为它们很古怪, 而不是真正的类 ,甚至会绊倒有经验JavaScript开发人员

For more detail see .

有关更多详细信息,请参见 。

警告:请勿在生产中使用! (WARNING: Don’t use in production!)

At the time of this writing, Hooks are in alpha. Their API can change at any time.

在撰写本文时, Hooks处于alpha状态。 他们的API可以随时更改。

I recommend you experiment, have fun, and use Hooks in your side projects, but not in production code until they’re stable.

我建议您尝试一下,玩得开心,并在您的辅助项目中使用Hook,但要在稳定之前再在生产代码中使用它们。

目标 (The goal)

We’ll be building a responsive Fixed-Data-Table. It won’t be too narrow or too wide for our page, it’ll fit just right!

我们将构建一个响应式固定数据表。 它对于我们的页面来说不会太窄或太宽,它恰好适合!

建立 (Setup)

Here are the and links.

这是和链接。

git clone https://github.com/yazeedb/Responsive-FDT2-Hooks/cd Responsive-FDT2-Hooksnpm install

The master branch has the finished project, so checkout the start branch if you wish to follow along.

master分支具有完成的项目,因此,如果您希望继续,请签出start分支。

git checkout start

git checkout start

And run the project.

并运行该项目。

npm start

npm start

The app should be running on localhost:3000. Let’s start coding.

该应用程序应在localhost:3000上运行。 让我们开始编码。

导入表格样式 (Importing table styles)

First you’ll want to import FDT2’s stylesheet in index.js, so your table doesn’t look whacky.

首先,您需要将FDT2的样式表导入到index.js ,这样您的表就不会显得古怪。

生成伪造数据 (Generating fake data)

Our table needs data, right? Create a file in src folder called getData.js.

我们的表需要数据,对吧? 在src文件夹中创建一个名为getData.js文件。

We’ll use the awesome library to generate our data. It already came with your npm install.

我们将使用很棒的库来生成我们的数据。 它已经随npm install

Here’s the source if you want to copy/paste.

如果您要复制/粘贴,则为以下来源。

import faker from 'faker';const createFakeRowData = () => ({  firstName: faker.name.firstName(),  lastName: faker.name.lastName(),  email: faker.internet.email(),  city: faker.address.city(),  salary: faker.random    .number({      min: 50000,      max: 500000    })    .toLocaleString('en-US', {      style: 'currency',      currency: 'USD'    })});export default () => Array.from({ length: 2000 }, createFakeRowData);

createFakeRowData returns an object with a full name, email, city, and salary in US dollars.

createFakeRowData返回具有全名,电子邮件,城市和薪水(以美元为单位)的对象。

Our exported function returns 2000 of them.

我们的导出函数返回2000个。

无响应的表 (The unresponsive table)

We have our data, let’s code up the table now.

我们有数据,现在让我们对表进行编码。

At the top of index.js, import our data and FDT2 components.

index.js的顶部,导入我们的数据和FDT2组件。

import { Table, Column, Cell } from 'fixed-data-table-2';import getData from './getData';

And use them like so.

并像这样使用它们。

function App() {  const data = getData();  return (    
First Name} width={130} cell={({ rowIndex, columnKey }) => { return
{data[rowIndex][columnKey]}
; }} />
Last Name} width={130} cell={({ rowIndex, columnKey }) => { return
{data[rowIndex][columnKey]}
; }} />
Email} width={320} cell={({ rowIndex, columnKey }) => { return
{data[rowIndex][columnKey]}
; }} />
City} width={180} cell={({ rowIndex, columnKey }) => { return
{data[rowIndex][columnKey]}
; }} />
Salary} width={180} cell={({ rowIndex, columnKey }) => { return
{data[rowIndex][columnKey]}
; }} />
);}

We configure the table with our data and create a Column for each field we want displayed.

我们使用数据配置表,并为要显示的每个字段创建一个Column

getData objects contain a first/last name, email, city, and salary, so we need a column for each.

getData对象包含名字/姓氏,电子邮件,城市和薪水,因此我们需要每个列。

Our UI is now looking like this.

我们的用户界面现在看起来像这样。

Try resizing your browser window, you’ll notice it isn’t responsive at all. It’s either too big or too small for your viewport and can leave excess space.

尝试调整浏览器窗口的大小,您会发现它根本没有响应。 视口太大或太小,都会留下多余的空间。

逃到不纯 (Escape to the impure)

As we’ve learned, React’s declarative nature lets you write your UI using pure, deterministic, and easily testable functions.

如我们所知,React的声明性使您可以使用纯净,确定性和易于测试的函数编写UI。

The same input should always return the same output.

相同的输入应始终返回相同的输出。

However, we sometimes need to visit the “impure” world, for DOM manipulation, adding events such as listeners, subscriptions, and timers.

但是,有时我们需要访问“不纯”世界,以进行DOM操作,添加诸如侦听器,订阅和计时器之类的事件。

HOCS和渲染道具 (HOCS and render props)

Render props and higher-order components (HOCS) are the standard solution, but have some tradeoffs that Hooks are now trying to solve.

渲染道具和高阶组件(HOCS)是标准解决方案,但需要Hooks现在尝试解决的一些权衡。

使用挂钩 (Using Hooks)

Hooks are the new escape hatch to use imperative code. In our case, getting the window size is the effect we’re after.

钩子是使用命令性代码的新的逃生舱口。 在我们的例子中,获得窗口大小是我们所追求的。

Create a new file called useWindowSize.js.

创建一个名为useWindowSize.js的新文件。

We’ll need two things to achieve this:

我们需要两件事来实现这一目标:

  1. Listen to the window’s resize event, so we’re notified of when it changes

    监听窗口的resize事件,以便在窗口发生变化时得到通知

  2. Save the width/height to share with our table

    保存宽度/高度以与我们的表共享

Two hooks can help:

两个钩子可以帮助:

  1. useEffect

    useEffect

  2. useState

    useState

useEffect (useEffect)

This will likely replace your componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle hooks once it’s stabilized.

一旦稳定下来,这很可能会替换您的componentDidMountcomponentDidUpdatecomponentWillUnmount生命周期挂钩。

useEffect's perfect for most initialization logic and reading the DOM.

useEffect对于大多数初始化逻辑和读取DOM来说是完美的。

It’s where we’ll set up our window resize event listeners.

在这里,我们将设置窗口resize事件监听器。

For more detail, see .

有关更多详细信息,请参见 。

useState (useState)

Super simple, this Hook returns a stateful value and a function to update it. Once we capture the window’s width/height, we’ll have useState track it.

这个挂钩非常简单,它返回一个有状态值和一个更新它的函数。 一旦捕获了窗口的宽度/高度,我们将使用useState跟踪它。

编写我们的自定义钩子 (Writing our custom Hook)

According to :

根据 :

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.

自定义挂钩是一个JavaScript函数,其名称以“ use”开头,并且可以调用其他挂钩。

Our custom hook will be called useWindowSize, and it’ll call the useState and useEffect hooks.

我们的自定义挂钩将称为useWindowSize ,它将称为useStateuseEffect挂钩。

This Hook’s mainly from ’s useWindowSize on .

这个Hook主要来自useWindowSize上的 。

// `useWindowSize.js`import { useState, useEffect } from 'react';export default () => {  const getSize = () => {    return {      width: window.innerWidth,      height: window.innerHeight    };  };  const [windowSize, setWindowSize] = useState(getSize);  useEffect(() => {    const handleResize = () => {      setWindowSize(getSize());    };    window.addEventListener('resize', handleResize);    return () => {      window.removeEventListener('resize', handleResize);    };  }, []);  return windowSize;};

Let’s break this down.

让我们分解一下。

获取窗口大小 (Getting the window size)

const getSize = () => {  return {    width: window.innerWidth,    height: window.innerHeight  };};

getSize simply returns the window’s innerWidth and innerHeight.

getSize只是返回窗口的innerWidthinnerHeight

初始化useState (Initializing useState)

const [windowSize, setWindowSize] = useState(getSize);

useState can take an initial value or a function that returns a value.

useState可以采用初始值或返回值的函数。

In this case we want the window’s dimensions to start, so getSize is the perfect initializer.

在这种情况下,我们希望窗口的尺寸开始,因此getSize是理想的初始化程序。

useState then returns an array, the first index is the value and the second index is the updater function.

useState然后返回一个数组,第一个索引是值,第二个索引是updater函数。

配置useEffect (Configuring useEffect)

useEffect(() => {  const handleResize = () => {    setWindowSize(getSize());  };  window.addEventListener('resize', handleResize);  return () => {    window.removeEventListener('resize', handleResize);  };}, []);

useEffect takes a function that will run your desired effect.

useEffect带有将运行您想要的效果的函数。

Whenever the window size changes, handleResize sets the state by giving setWindowSize the latest width/height.

每当窗口大小更改时, handleResize通过为setWindowSize最新的宽度/高度来设置状态。

Cleanup Logic

清理逻辑

Our effect function then returns a new function, which useEffect recognizes as cleanup logic.

然后,我们的效果函数将返回一个新函数useEffect将其识别为清除逻辑。

return () => {  window.removeEventListener('resize', handleResize);};

When we leave the page or somehow unmount our component, this cleanup function runs and removes the resize event listener. This helps prevent memory leaks.

当我们离开页面或以某种方式卸载组件时,此清理功能将运行并删除resize事件侦听器。 这有助于防止内存泄漏。

useEffect’s Second Argument

useEffect的第二个参数

useEffect's first argument is the function handling our logic, but we also gave it a second argument: an empty array.

useEffect的第一个参数是处理逻辑的函数,但我们还给了它第二个参数:空数组。

useEffect(() => { ... }, []); // empty array

Why an empty array?

为什么是空数组?

useEffect's second argument is an array of values to watch over. If any of those values change useEffect runs again.

useEffect的第二个参数是要监视的值的数组。 如果这些值中的任何一个发生更改, useEffect将再次运行。

We’re just setting/removing event listeners, which only needs to happen once.

我们只是设置/删除事件监听器,只需要发生一次即可。

An empty array is how we communicate “just run once” to useEffect.

空数组是我们交流“只运行一次”以使用useEffect

Empty array = no values ever change = just run once

空数组=值无变化=仅运行一次

返回窗口大小 (Return windowSize)

Now that our effect’s set up, just return windowSize. As the browser’s resized, windowSize will be updated.

现在我们的效果已经设置好了,只需要返回windowSize 。 随着浏览器大小的调整, windowSize将被更新。

使用我们的自定义挂钩 (Using our custom Hook)

Time to throw our Hook at Fixed-Data-Table2!

是时候把我们的固定数据表2钩了!

Back in index.js, go ahead and import useWindowSize.

返回index.js ,继续并导入useWindowSize

And use it like so.

并像这样使用它。

For fun you can console.log(windowSize) and watch it update in real-time.

为了好玩,您可以console.log(windowSize)并观看它的实时更新。

Cool, we get back an object of the window’s width and height!

太酷了,我们得到一个窗口widthheight的对象!

Instead of hardcoding our table’s width and height, we can use our Hook’s exposed state.

无需硬编码表的宽度和高度,我们可以使用Hook的暴露状态。

Now your table should adjust to the window’s dimensions.

现在您的表应该调整到窗口的尺寸。

I hope you enjoyed this tutorial!

希望您喜欢本教程!

翻译自:

react hooks使用

转载地址:http://ifwzd.baihongyu.com/

你可能感兴趣的文章
未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”
查看>>
Erdos
查看>>
docker初学
查看>>
面向对象的程序第三次实验作业
查看>>
Windows 安装启动apache时出现错误的解决方法
查看>>
Object.prototype.toString()
查看>>
int.Parse()与int.TryParse()
查看>>
c#调用钩子
查看>>
最近最少使用队列算法
查看>>
ONOS:负载均衡路由算法及应用开发(二)
查看>>
把js写到链接a标签的href中和写到onclick中的区别
查看>>
压缩解压缩命令
查看>>
MySQL基于binlog主从复制
查看>>
HDU 1394(归并求逆序对)
查看>>
配置 Windows 下的 nodejs C++ 模块编译环境 安装 node-gyp
查看>>
我和Socket的第一次亲密接触
查看>>
2016/09/22
查看>>
2016/09/02
查看>>
项目中遇到的Redis缓存问题
查看>>
Effective Java 之-----静态工厂与构造器
查看>>