小编Lau*_*ris的帖子

如何在带有 Typescript 的 React 项目中组织类型定义

我已经在我的项目中使用打字稿一个月了,但我一直在努力解决一些疑问。

是否有一种模式/推荐的方式来组织项目架构中的类型?

假设我们有一个具有以下接口的上下文:

export type ToastMessageType = 'info' | 'success' | 'error';

export interface ToastMessageData {
  id: string;
  title: string;
  description: string;
  type: ToastMessageType;
}

export interface ToastsStateContextData {
  messages: ToastMessageData[];
}

export interface ToastsDispatchContextData {
  addToast: (message: Omit<ToastMessageData, 'id'>) => void;
  removeToast: (id: string) => void;
}

Run Code Online (Sandbox Code Playgroud)

还有另一个称为ToastMessage接收message道具的组件,其类型为ToastMessageData

interface ToastMessageProps {
  message: ToastMessageData;
  style: React.CSSProperties;
}

const ToastMessage: React.FC<ToastMessageProps> = ({ message, style }) => {
Run Code Online (Sandbox Code Playgroud)

我觉得从组件内部的上下文中导入接口很奇怪,所以发生了一些错误。

大家有什么推荐吗?

frontend typescript reactjs

12
推荐指数
1
解决办法
4501
查看次数

节点错误 - 在 MakeCallback 中使用域属性已被弃用

我在执行请求时收到此错误。

(节点:3993)[DEP0097] 弃用警告:不推荐在 MakeCallback 中使用域属性。请改用 MakeCallback 的 async_context 变体或 AsyncResource 类。

那是我的控制器 的代码:AppointmentController队列的代码:Queue Nodemailer:Mail

async delete(req, res) {
    const { appointment_id } = req.params;

    if (!appointment_id) {
      return res.status(404).json({
        error: "It's not possible to cancel an appointment with passing an id",
      });
    }

    const appointment = await Appointment.findByPk(appointment_id, {
      include: [
        {
          model: Restaurant,
          as: 'restaurant',
          attributes: ['id', 'name', 'provider_id'],
          include: [
            {
              model: Provider,
              foreignKey: 'provider_id',
              as: 'provider',
            },
          ],
        },
        {
          model: User,
          as: …
Run Code Online (Sandbox Code Playgroud)

javascript queue redis node.js

9
推荐指数
2
解决办法
1万
查看次数

如何使用 Jest 测试 document.eventListener

我有事件侦听器,它将调用处理身份验证的函数。我想测试一下,如果该函数接收到错误的数据,它将返回一个数据,如果没有,将返回另一个数据。

但我不明白如何模拟该功能并对此做出期望。

这就是听众:

window.addEventListener('message', authentication, false);
Run Code Online (Sandbox Code Playgroud)

我想根据结果做出期望的函数:

export function* authentication({ data }) {
  // Data structure {
  //   action: 'authentication',
  //   id: '7293847829109932,
  //   displayName: 'User Name',
  //   avatar: 'https://steamcommunity.com/images/user.png',
  //   access: 'access_token_string',
  //   refresh: 'refresh_token_string',
  // }

  if (data.action === 'authentication') {
    localStorage.setItem('dualbits:access', data.access);
    localStorage.setItem('dualbits:refresh', data.refresh);
  }

  // Will dispatch the success action if the data is correct
  yield put(signInSuccess(data));
}
Run Code Online (Sandbox Code Playgroud)

到目前为止所做的是模拟窗口全局变量和 addEventListener 方法。我也实现了这个期望:

expect(window.addEventListener).toHaveBeenCalledWith(
  'message',
  authentication,
  false
);
Run Code Online (Sandbox Code Playgroud)

javascript testing frontend jestjs redux

8
推荐指数
1
解决办法
4万
查看次数

Docker 和 Windows - 连接尝试失败,因为连接方在一段时间后没有正确响应

我安装了 docker 工具箱,但是当我尝试创建容器时,它给了我这个错误。返回版本,但无法创建容器。

操作系统:Windows 10 家庭版

ERROR: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
Run Code Online (Sandbox Code Playgroud)

docker docker-toolbox

8
推荐指数
2
解决办法
1万
查看次数

AdonisJS - 如何根据 Antl Provider 的语言环境返回验证消息

我正在对我的 API 应用国际化,但我遇到了一些与 Antl 和验证消息相关的问题。

对于标准响应消息,我将根据用户设置的区域设置返回。我创建了一个切换语言环境的路由,并设置为一个 cookie 和一个全局中间件,以从 cookie 中获取语言环境,然后我只返回存储在语言环境资源中的消息。

全局中间件:

class Locale {
  async handle ({ request, antl }, next) {
    const lang = request.cookie('lang')

    if (lang) {
      antl.switchLocale(lang)
    }

    await next()
  }
}
Run Code Online (Sandbox Code Playgroud)

路线:

Route.get('/switch/:lang', ({ params, antl, request, response }) => {
  // Getting the current available locales
  const locales = antl.availableLocales()

  try {
    // Saving into cookies
    if (locales.indexOf(params.lang) > -1) {
      response.cookie('lang', params.lang, { path: '/' })
    }

    return response.status(200).send({ message: 'Locale changed succesfully' }) …
Run Code Online (Sandbox Code Playgroud)

javascript backend node.js adonis.js lucid

7
推荐指数
1
解决办法
1315
查看次数

听 EACCES:权限被拒绝 0.0.0.0:8080

我尝试在公共文件夹中运行实时服务器,但随后显示此错误:

C:\Users\Luiz\Desktop\udemy\react-course-projects\indecision-app>live-server public
Error: listen EACCES: permission denied 0.0.0.0:8080
Run Code Online (Sandbox Code Playgroud)

javascript reactjs

6
推荐指数
1
解决办法
6348
查看次数

Routes.push() 在 NextJS 中未按预期工作

当用户尝试在未经身份验证的情况下访问应用程序的仪表板时,我试图将用户重定向到主页,但 Route.push() 不起作用。

我尝试将 Router.push('/') 更改为 Router.push('/hey') -> 一个不存在的页面,这有效,路由发生了变化。另外,当我尝试访问像 Router.push('/auth/signin') 这样的路径时,它不起作用,而 Router.push('/auth') 有效

import { isAuthenticated } from "../helpers/auth";
import { Component } from "react";
import { Router } from "../routes";

class Ads extends Component {
  // static async getInitialProps(ctx) {
  //   if (ctx && ctx.req) {
  //     console.log(ctx);
  //     //ctx.res.writeHead(302, { Location: `/` });
  //     ctx.res.end();
  //   } else {
  //     console.log("client side");
  //     console.log(localStorage.getItem("auth-token"));
  //   }
  // }

  handleAuthentication = () => {
    if (localStorage.getItem("auth-token")) {
      return true; …
Run Code Online (Sandbox Code Playgroud)

routes token reactjs next.js

5
推荐指数
1
解决办法
3万
查看次数

Github Api 授权问题

我正在尝试使用 Github Api 进行授权请求,传递用户名和密码。但它不起作用,我收到 401 状态代码。

文档中有一部分说

To use Basic Authentication with the GitHub API, simply send the username and password associated with the account.
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

this.api
        .post('/user', { username: 'Example', password: '1234' })
        .then(res => resolve(res.data))
        .catch(err => reject(err));
Run Code Online (Sandbox Code Playgroud)

javascript authorization github-api axios

5
推荐指数
1
解决办法
4183
查看次数

当重定向到相同路径名但具有不同路由参数时,History.push 不起作用

我有以下路线"/event/:eventId"

当用户从主页点击卡片时,它会重定向到活动页面(到目前为止一切正常)

但在事件页面内部,我有其他卡重定向到具有不同 ID 作为路由参数的其他事件页面,然后单击然后仅更改路径,但不会重新呈现页面。

看来,如果我位于具有相同路径名的页面中,无论路由参数发生变化,它都不会重新渲染页面。

我尝试使用<Link>组件代替history.push但它也不起作用。

这就是重定向功能:

 const onCardClick = () => {
    history.push(
      EVENT_PAGE_LOCATION.toUrl({
        eventId: event?.id,
      }),
    );
  };


Run Code Online (Sandbox Code Playgroud)

javascript frontend reactjs react-router

5
推荐指数
1
解决办法
6001
查看次数

Jest 测试 - 请在入口点的顶部添加“import “reflect-metadata””

我正在开发一个使用依赖注入的应用程序tsyringe。这是接收存储库作为依赖项的服务的示例:

import { injectable, inject } from 'tsyringe'

import IAuthorsRepository from '@domains/authors/interfaces/IAuthorsRepository'

@injectable()
export default class ListAuthorsService {
  constructor (
    @inject('AuthorsRepository')
    private authorsRepository: IAuthorsRepository
  ) {}
Run Code Online (Sandbox Code Playgroud)

和依赖项容器:

import { container } from 'tsyringe'

import IAuthorsRepository from '@domains/authors/interfaces/IAuthorsRepository'
import AuthorsRepository from '@domains/authors/infra/typeorm/repositories/AuthorsRepository'

container.registerSingleton<IAuthorsRepository>(
  'AuthorsRepository',
  AuthorsRepository
)

export default container
Run Code Online (Sandbox Code Playgroud)

在测试中,我不想使用在容器上注册的依赖项,而是通过参数传递模拟实例。

let authorsRepository: AuthorsRepositoryMock
let listAuthorsService: ListAuthorsService

describe('List Authors', () => {
  beforeEach(() => {
    authorsRepository = new AuthorsRepositoryMock()
    listAuthorsService = new ListAuthorsService(authorsRepository)
  })
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

tsyringe 需要反射 polyfill。请在入口点的顶部添加“import “reflect-metadata””。

我的想法是 …

node.js typescript jestjs tsyringe

5
推荐指数
2
解决办法
1565
查看次数

Apollo 客户端 - 在终止链接上调用 concat,这不会产生任何效果

我有以下阿波罗链接:

 const link = ApolloLink.from([
    serializingLink,
    httpAuthLink,
    queueLink,
    retryLink,
    errorLink,
    uploadLink,
    httpLink
  ]);

Run Code Online (Sandbox Code Playgroud)

它们都具有正确的设置添加新链接后,该错误开始出现在控制台中:

Error: You are calling concat on a terminating link, which will have no effect
Run Code Online (Sandbox Code Playgroud)

通过阅读另一期,我发现这可能与数组内部链接的顺序有关。

apollo graphql apollo-client

1
推荐指数
1
解决办法
1638
查看次数