本文共 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分享这个例子很酷。
They’re functions that give you React features like state and lifecycle hooks without ES6 classes.
它们是为您提供React功能的功能,例如没有ES6类的状态和生命周期挂钩。
Some benefits are
一些好处是
avoiding ES6 classes, because they’re quirky, not actually classes, and trip up even experienced JavaScript developers
避免使用ES6类,因为它们很古怪, 而不是真正的类 ,甚至会绊倒有经验JavaScript开发人员
For more detail see .
有关更多详细信息,请参见 。
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,但要在稳定之前再在生产代码中使用它们。
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!
我们将构建一个响应式固定数据表。 它对于我们的页面来说不会太窄或太宽,它恰好适合!
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
上运行。 让我们开始编码。
First you’ll want to import FDT2’s stylesheet in index.js
, so your table doesn’t look whacky.
首先,您需要将FDT2的样式表导入到index.js
,这样您的表就不会显得古怪。
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个。
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.
尝试调整浏览器窗口的大小,您会发现它根本没有响应。 视口太大或太小,都会留下多余的空间。
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操作,添加诸如侦听器,订阅和计时器之类的事件。
Render props and higher-order components (HOCS) are the standard solution, but have some tradeoffs that Hooks are now trying to solve.
渲染道具和高阶组件(HOCS)是标准解决方案,但需要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:
我们需要两件事来实现这一目标:
Listen to the window’s resize
event, so we’re notified of when it changes
监听窗口的resize
事件,以便在窗口发生变化时得到通知
Two hooks can help:
两个钩子可以帮助:
useEffect
useEffect
useState
useState
This will likely replace your componentDidMount
, componentDidUpdate
, and componentWillUnmount
lifecycle hooks once it’s stabilized.
一旦稳定下来,这很可能会替换您的componentDidMount
, componentDidUpdate
和componentWillUnmount
生命周期挂钩。
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
跟踪它。
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
,它将称为useState
和useEffect
挂钩。
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.
让我们分解一下。
const getSize = () => { return { width: window.innerWidth, height: window.innerHeight };};
getSize
simply returns the window’s innerWidth
and innerHeight
.
getSize
只是返回窗口的innerWidth
和innerHeight
。
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(() => { 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
空数组=值无变化=仅运行一次
Now that our effect’s set up, just return windowSize
. As the browser’s resized, windowSize
will be updated.
现在我们的效果已经设置好了,只需要返回windowSize
。 随着浏览器大小的调整, windowSize
将被更新。
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
!
太酷了,我们得到一个窗口width
和height
的对象!
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/