js函数里的next()_在Next.js中使用管道函数getServerSideProps

js函数里的next()

Jamstack心态 (Jamstack mentality)

The React and web development community has witnessed in recent years the rise in popularity of frameworks that embrace the Jamstack ideas. These platforms offer the promise of more performant web pages by using a variety of techniques. While Gatsby has built an amazing set of tools dedicated to generating static sites with ease, Next.js has focused on offering flexibility in how it fetches data and renders pages.

近年来,React和Web开发社区见证了包含Jamstack思想的框架的流行 。 这些平台通过使用多种技术提供了性能更高的网页的希望。 尽管盖茨比(Gatsby )建立了一套令人惊叹的工具,专门用于轻松生成静态网站,但Next.js专注于在如何获取数据和呈现页面方面提供灵活性。

While both of these platforms have their strengths and weaknesses, it is important to establish a strong data fetching strategy in any project. Next.js offers two main ways of fetching data before the page is loaded client-side:

虽然这两个平台都有其优点和缺点,但是在任何项目中建立强大的数据获取策略都是很重要的。 Next.js提供了两种在客户端加载页面之前获取数据的主要方式:

In this tutorial, we will focus on building a piping function to simplify the organization of getServerSideProps functions.

在本教程中,我们将专注于构建管道函数以简化getServerSideProps函数的组织。

管道功能 (Pipe functions)

A pipe function is not a new concept for people familiar with functional programming. The idea is to initiate a series of functions that push information downwards transforming along the way the information into a desired format. Here is a simple example:

对于熟悉函数式编程的人来说,管道函数并不是一个新概念。 想法是启动一系列功能,这些功能将信息向下推,从而沿信息转换为所需格式的方式。 这是一个简单的示例:

const double = (num) => num * 2;const add1 = (num) => num + 1;pipe(double, add1)(5); // equivalent of add1(double(5))// returns 11

The idea between a pipe function is pretty simple to understand and to implement in JavaScript. However, there is an interesting challenge around building such a functionality when working with promises and asynchronous data fetching.

管道函数之间的想法非常容易理解,并可以在JavaScript中实现。 但是,在处理Promise和异步数据提取时,围绕构建这样的功能存在一个有趣的挑战。

The .then notation is already operating similarly but does not serve our purpose of having a reusable function that can pass props to Next.js' getServerSideProps. Let's get down to business and implement such a function in TypeScript.

.then表示法已经类似地运行,但是不能达到我们具有可重用功能的目的,该功能可以将prop传递给Next.js的getServerSideProps 。 让我们开始做生意,并在TypeScript中实现这样的功能。

type PipedGetServerSideProps = (arg?: any) => Promise<any> | any;export const ssrPipe = (...functions: PipedGetServerSideProps[]) => async (input: any): Promise<{props: Object;}> => {return {props: await functions.reduce((chain, func) => chain.then(func),Promise.resolve(input)),};};

There are 4 important aspects to understand in this small code snippet:

在此小代码段中有四个重要方面需要理解:

  1. The initial argument will be resolved in order to start a promise chain.

    初始参数将被解析以便启动承诺链。
  2. By using the spread operator, we can accept an unlimited number of piped functions.

    通过使用传播运算符,我们可以接受无限数量的管道函数。
  3. Each function receives as an argument the resolved value of the previous Promise.

    每个函数都将前一个Promise的解析值作为参数接收。
  4. We end up returning the data in the format Next.js is expecting in getServerSideProps.

    我们最终在getServerSideProps返回Next.js期望的格式的数据。

With this in mind, let’s explore a real life use case where we need to fetch an user from a session and then use this user ID to fetch information about him. We will not go into implementation details in order to focus on usage of the function.

考虑到这一点,让我们探索一个实际的用例,其中我们需要从会话中获取用户,然后使用该用户ID来获取有关该用户的信息。 为了专注于功能的使用,我们将不介绍实现细节。

用法示例 (Example usage)

The first thing to note is that our pipe function is tailored to return an object containing the props property. This is to ensure compatibility with getServerSideProps, but forces us to only use our pipe function with Next.js. (please read the related documentation if you are not familiar with the concept):

首先要注意的是,我们的管道函数经过了精心设计,可以返回包含props属性的对象。 这是为了确保与getServerSideProps兼容,但是迫使我们仅将管道函数与Next.js一起使用。 ( 如果您不熟悉此概念,请阅读相关文档 ):

export const getServerSideProps: GetServerSideProps = ssrPipe(withUser,withUserSubscriptions);

The first function will then receive as an argument the Next.js context. It can then proceed to fetch the user session and information based the context object and send along the information to the next function in line:

然后,第一个函数将接收Next.js上下文作为参数。 然后,它可以继续基于上下文对象获取用户会话和信息,并将信息一起发送给下一个函数:

// first functionconst withUser async (context) => {const { req, res } = context;// data fetching and munging goes herereturn { userId: "123" };

The next function passed will then receive the previous function’s return value as an argument. It can then proceed to fetch new information and format it to be passed down the chain. In our example, this is our last function, so we will return an object representing the value of our Page’s props:

然后,传递的下一个函数将接收前一个函数的返回值作为参数。 然后,它可以继续获取新信息并将其格式化以向下传递。 在我们的示例中,这是我们的最后一个函数,因此我们将返回一个表示Page属性值的对象:

const withUserSubscriptions async ({ userId }) => {// additional data fetching and munging goes hereconst res = await fetch(".../somewhere");const data = await res.json();return {userId,subscriptions: data,};};

An unlimited number of functions can then work together to achieve a pipeline of information. The last function is responsible to return the final Props object. This object will then be injected as a prop to the next.js Page component:

然后,无限数量的功能可以一起工作以实现信息流水线。 最后一个函数负责返回最终的Props对象。 然后,该对象将作为道具注入next.js Page组件:

function Page({ userId, subscriptions }) {return (<p>{userId} is suscribed to {subscriptions.toString()}</p>);}export const getServerSideProps: GetServerSideProps = ssrPipe(withUser,withUserSubscriptions);

结论 (Conclusion)

  • A pipe function is helpful to push down information to the next function.

    管道功能有助于将信息下推到下一个功能。
  • The same functionality can be achieved with a single function, but piping helps code organization.

    单个功能可以实现相同的功能,但是管道可以帮助代码组织。
  • Next.js offers a great set of tools in React projects that, when well-organized, provide a great developer experience.

    Next.js在React项目中提供了很多工具,如果组织得当,它们将提供出色的开发人员体验。

Originally published at https://frontend-devops.com.

最初发布在 https://frontend-devops.com

翻译自: https://medium.com/swlh/using-a-pipe-function-in-next-js-getserversideprops-77d98d2fae64

js函数里的next()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码是用于更新激活值的函数函数接受四个参数:`i` 表示当前层的索引,`pruned_model` 表示被修剪的模型,`activation` 表示当前层的激活值,`CBL_idx` 是一个列表,其包含需要修剪的卷积层的索引。 首先,通过 `next_idx = i + 1` 计算下一层的索引。 然后,判断下一层的类型是否为卷积层。如果是卷积层,则执行下面的代码块。 在代码块,首先获取下一层的卷积操作符 `next_conv`。然后,计算卷积核在空间维度上的和,即 `conv_sum = next_conv.weight.data.sum(dim=(2, 3))`。这是为了得到每个卷积核在该层输出特征图上的感受野大小。 接下来,通过矩阵乘法 `conv_sum.matmul(activation.reshape(-1, 1))` 将卷积核的感受野大小与当前层的激活值相乘,得到一个偏移量 `offset`。这个偏移量表示下一层的偏置项需要调整的大小。 然后,判断下一层是否在需要修剪的卷积层索引列表 `CBL_idx` 。如果在列表,则表示该层是 Batch Normalization 层,需要更新其 running_mean。通过 `next_bn = pruned_model.module_list[next_idx][1]` 获取下一层的 Batch Normalization 操作符,然后使用 `next_bn.running_mean.data.sub_(offset)` 减去偏移量来更新其 running_mean。 如果下一层不在需要修剪的卷积层索引列表,则表示该层是普通的卷积层,需要更新其偏置项。通过 `next_conv.bias.data.add_(offset)` 将偏移量加到下一层的偏置项上。 综上所述,这段代码的作用是根据当前层的激活值和下一层的类型,来更新下一层的偏置项或 running_mean。这样可以保持模型在修剪过程的准确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值