小编Phi*_*cks的帖子

VSCODE 和 GitHub Desktop 预提交挂钩:npx:找不到命令

我正在开始一个新的存储库,认为我应该使用最新的 Huksy v6,它是使用其设置指南从 LintStages 安装的:

npx mrm lint-staged

// package.json updated with:
"husky": ">=6",
"lint-staged": ">=10",
Run Code Online (Sandbox Code Playgroud)

这将添加必要的包并添加 husky 文件,包括预提交文件:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
Run Code Online (Sandbox Code Playgroud)

当我在终端中运行我的提交时,它工作正常。但是,如果我尝试在 GitHub Desktop 或 VSCode 中运行我的提交(我知道一些队友会这样做),则会导致两者出现错误:

npx:未找到命令。husky - 预提交挂钩退出,代码为 127(错误)

我已经安装了 npx:

npx -v
// 6.14.10
Run Code Online (Sandbox Code Playgroud)

如果我尝试在 globall 中安装,如其他 StackOverflow 建议中所述,它会返回有关现有位置的警告(带 & 不带 out sudo):

呃!EEXIST:文件已存在,符号链接 '../lib/node_modules/npx/index.js' -> '/Users/plucks/.nvm/versions/node/v14.15.4/bin/npx' npm 错误!文件存在:/Users/plucks/.nvm/versions/node/v14.15.4/bin/npx npm 错误!删除现有文件并重试,或运行 npm npm ERR! 使用 --force 鲁莽地覆盖文件。

我可以做些什么来让 VSCode 和 GitHub Desktop 等程序可以运行吗?

visual-studio-code github-desktop husky lint-staged

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

如何在提取之间从 useSWR 导出“加载”而无需重新验证?

有人问我一个关于 SWR“加载”状态的问题:

如何在不同的 URL 获取之间从 SWR 创建加载状态?

他们的文档让它看起来很简单:

  const { data, error } = useSWR(`/api/user/${id}`, fetcher)
  const isLoading = !error && !data;

Run Code Online (Sandbox Code Playgroud)

然而,这个逻辑在钩子/组件第一次渲染后似乎失败了。第一次渲染数据是undefined. 然后加载并且数据成为 UI 中要使用的值。

假设我id通过 UI 更改并希望显示加载指示器。因为data不再是undefined,所以同样的逻辑失败了。

还返回了一个附加项目isValidating。所以我更新了我的逻辑:

const isLoading = (!data && !error) || isValidating
Run Code Online (Sandbox Code Playgroud)

然而,在以下情况下这可能是正确的:

正在加载请求或重新验证。

因此理论上,其他原因会导致我的组件重新渲染。这可能会无意中导致“重新验证”并显示触发器加载状态。这可能会意外地暂时破坏 UI。

那么如何在 URL 更改之间获得“加载”而不需要重新验证呢?我正在尝试复制 graphQL Apollo 客户端返回的方式const { loading, error, data } = useQuery(GET_DOGS);

reactjs next.js swr

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

Jest spyOn 不是 Class 或 Object 类型的函数

我熟悉在 Class 或 Object 方法上设置间谍,但是当函数只是一个导出默认值时怎么办 - 这样方法本身是独立的,就像一个实用程序?

我有一些现有的代码,如下所示:

const Funct1 = props => {
  if(props){
    Funct2(args);
  }
  // or return something
};
const Funct2 = props => {
  // do something
  return true
};
export default Funct1;  //Yes the existing export is named the same as the "entry" method above.
Run Code Online (Sandbox Code Playgroud)

而且,例如,我想监视Funct1被调用并Funct2返回 true。

import Funct1 from "../../../src/components/Funct1";
describe("Test the Thing", () => {
    it("New Test", () => {
        let props = {
            active: true,
            agentStatus: "online"
        }; …
Run Code Online (Sandbox Code Playgroud)

javascript jasmine jestjs

13
推荐指数
3
解决办法
8034
查看次数

使用 className 反应酶 Jest 测试组件

我正在关注.find()的酶示例和这个 GitHub示例-jest示例以获得一个基本组件来测试和验证最外层元素是否className存在,我不明白为什么这没有通过:

// 反应组件

class VisitorShortcut extends Component {
//all the props & lifecycle hooks here
render() {
        return (
            <div className="visitor-shortcuts"> // <-- this className is being tested
                <div
                    onClick={e => e.stopPropagation()}
                    className="dropdown open"
                >
                    <ul
                        style={style}
                        ref="shortcutContainer"
                        className={"dropdown-menu "}
                    >
                        {results}
                    </ul>
                </div>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

// 测试文件

import React from "react";
import { shallow, mount } from "enzyme";
import VisitorShortcut from "../VisitorShortcut";

describe("Shortcuts", () => {
  test("The main …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs enzyme

10
推荐指数
2
解决办法
3万
查看次数

GitHub 桌面 Husky 预提交钩子没有

我按照许多其他项目安装了(在 Mac OS11 上)husky@4lint-staged终端命令流程git add .git commit -m 'something'流程工作正常:Husky 的预提交挂钩和lint-staged命令已成功获取。然而,Github Desktop 预提交挂钩似乎没有表现。

我尝试查看该文件.git/hooks/pre-commit,它就在那里:

#!/bin/sh
# husky

# Created by Husky v4.3.8 (https://github.com/typicode/husky#readme)
#   At: 3/7/2021, 12:09:26 PM
#   From: /Users/admin/devProj/prject/node_modules/husky (https://github.com/typicode/husky#readme)

. "$(dirname "$0")/husky.sh"
Run Code Online (Sandbox Code Playgroud)

命令:

...
        "husky": "^4.3.8",
        "lint-staged": "^10.5.4",
...
"husky": {
        "hooks": {
            "pre-commit": "tsc --noEmit && lint-staged"
        }
    },
    "lint-staged": {
        "**/*.(js|jsx|ts|tsx)": [
            "npm run lint:fix",
            "prettier --write"
        ]
    }
Run Code Online (Sandbox Code Playgroud)

GitHub Desktop 找不到此内容的任何其他原因吗?

github-desktop husky lint-staged git-husky

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

typescript-eslint 配置:.eslintrc 文件“模块”未定义

我正在按照typescript-eslint入门文档中的说明设置一个新项目。但是,在我的.eslintrc.js文件中,我收到一个错误:

'module' 未定义。eslint(no-undef)

现在,如果我eslint:recommendedextends配置中删除,这个错误就会消失。然而,ESLint喜欢debuggerconst iAmUnused = true不接受典型的规则,所以如果感觉有点像打鼹鼠。

为什么我的 ESLint 文件在我的项目根目录中并eslint:recommended启用时被拾取?我不想在我的文件中包含这个文件,.eslintignore因为在运行我的eslint命令时,它说这个文件已经被自动忽略了,但它不是???

ESLINTRC:

module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: '*/tsconfig.json',
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
  plugins: ['@typescript-eslint', 'jest', 'react', 'react-hooks'],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:jest/recommended',
    'plugin:prettier/recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'prettier',
    'prettier/@typescript-eslint',
  ],
  rules: {
    'no-unused-vars': 2,
  },
  env: {
    browser: true,
    es6: true,
    jest: true,
  },
  overrides: …
Run Code Online (Sandbox Code Playgroud)

typescript eslint eslintrc typescript-eslint

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

在动态路由上使用基于文件的路由器进行导航时遇到问题

基于文件的路由并没有完全适合我。早期的 NextJS pages文件路由很容易工作。由于某种原因,我还没有转换为基于世博路线的文件。可能是因为堆栈、选项卡和插槽的组合。我一直在阅读动态路线文档。当我从选项卡屏幕中导航到 时/pattern/[id],由于 Expo 找不到路线,翻译中有些内容丢失了。我尝试了各种各样的方法,但我认为这与我的文件夹结构有关。我想要的是:目的地/pattern/[id]是(选项卡)的子级,而不是搜索。

app
  |__(auth)
     |__ _layout.tsx
     |__(tabs)
       |__ index.tsx
       |__ _layout.tsx
       |
       |__ search
       | |__ index.tsx // <-- from where I navigate from
       | |__ _layout.tsx
       |
       |__ pattern // <-- where I want to navigate to
       |  |__ _layout.tsx
       |  |__ [id].tsx // <-- dynamic pattern id name 
       |__ // other tabs content is ok since no navigation
Run Code Online (Sandbox Code Playgroud)

这是我的选项卡的 _layout :

export default function TabLayout() {
  return …
Run Code Online (Sandbox Code Playgroud)

react-native expo expo-router

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

ESLint `no-confusing-arrow` “--fix”保存时格式冲突,与 Prettier?

似乎有一些规则让我的配置让系统知道使用 ESLint 并不总是有效。我在 VSCode 中启用了保存时的“自动格式”。

例如,ESLint 错误为no-confusing-arrow

getOptionSelected={option =>
   typeof option === 'string' ? option : option.description
}
Run Code Online (Sandbox Code Playgroud)

如果我运行eslint --fix它,它会更新以将括号括起来作为表达式:

getOptionSelected={option =>
   (typeof option === 'string' ? option : option.description)
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我保存,它会撤消更改并返回错误。

我的 ESLint 如下:

{
  "root": true,
  "parser": "@babel/eslint-parser",
  "extends": [
    "plugin:prettier/recommended",
    "plugin:jest/recommended",
    "plugin:testing-library/react",
    "airbnb",
    "eslint:recommended",
    "next"
  ],
  "plugins": ["prettier", "simple-import-sort"],
  "env": {
    "browser": true,
    "es6": true,
    "node": true,
    "jest": true
  },
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "settings": …
Run Code Online (Sandbox Code Playgroud)

eslint prettier prettier-eslint

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

为什么在测试期间 useParams 在带有包装器的测试环境中返回未定义?

我现在已经在 2 个不同的代码库中看到了这一点,但我很难过,因为它在实际浏览器中运行良好,但在测试中却没有:如果组件使用useParams钩子,则钩子会在测试中引发错误:

错误:未捕获 [类型错误:无法解构accountId“未定义”或“空”的属性。]

我正在使用 React 功能组件、React 测试库和 React-Router:

// 成分:

const Overview: FC = () => {
  const location = useLocation();
  console.log(location) // see below
  const { accountId } = useParams();
  console.log(accountId) // see below

  ... rest
}
Run Code Online (Sandbox Code Playgroud)

控制台日志似乎已正确找到参数:

console.log src/screens/Overview/index.tsx:66 accountId: nodata

console.log src/screens/Overview/index.tsx:64 location: { pathname: '/mix/overview/nodata', search: '', hash: '', state: undefined, key: 'bn6zvv' }

// 使用RTL 文档中推荐的包装器测试设置


function renderWithProviders(
  ui,
  {
    route = '/',
    params = routes.root, 
    history …
Run Code Online (Sandbox Code Playgroud)

reactjs react-router react-router-dom react-testing-library

6
推荐指数
2
解决办法
8598
查看次数

查看以横向拍摄的照片,以“纵向”方向查看,并保存以使其不旋转

"react-native-vision-camera": "^2.15.4",在我的 Expo 项目中使用(SDK 46,RN,0.69.9)。该expo-camera模块不支持不同的镜头,因此需要切换。

当我以纵向或横向方向拍照时,照片显示为photo.metadata.Orientation: 6

这让我很惊讶。

在此输入图像描述 在此输入图像描述

我希望在拍摄照片后旋转图像的预览,使其水平且更易于查看。它也垂直保存,因此在网络上,它的旋转也错误。

<Camera
  // Do not add enableZoomGesture since using the Animated lib
  // enableZoomGesture
  ref={cameraRef}
  photo
  device={device}
  isActive={isActive}
  format={formats?.[0]}
  animatedProps={animatedProps}
  orientation={'portrait'}
/>
Run Code Online (Sandbox Code Playgroud)

显然,相机组件中的orientation道具也没有按预期运行。

为什么元数据上的方向相同?如何让照片在拍摄后正确旋转,以便保存为以水平“纵向”方向查看?


编辑此后我尝试过react-native-orientation-locker. 虽然它不会锁定正在捕获的图像,但我至少可以在捕获事件之后自定义图像:

const capturePhoto = async () => {
    if (cameraRef?.current && !snapping) {
      setSnapping(true);
      const photo = await cameraRef.current.takePhoto({
        flash: flashMode,
      });

      let rotation = 0;

      if (orientation === OrientationType['LANDSCAPE-LEFT']) {
        rotation = -90;
      } else if …
Run Code Online (Sandbox Code Playgroud)

react-native expo react-native-vision-camera react-native-orientation-locker

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

使用 useTranslation 进行 next-i18next Jest 测试

测试库...总是很有趣。我next-i18next在我的 NextJS 项目中使用。我们正在使用useTranslation带有命名空间的钩子。

当我运行我的测试有一个警告:

console.warn react-i18next:: 您需要使用 initReactI18next 传入一个 i18next 实例

> 33 |   const { t } = useTranslation(['common', 'account']);
     |                 ^
Run Code Online (Sandbox Code Playgroud)

我已经尝试了react-i18next 测试示例中的设置,但没有成功。我也试过这个建议

以及只是试图嘲笑useTranslation但没有成功。

是否有更直接的解决方案来避免此警告?测试通过 FWIW...

test('feature displays error', async () => {
    const { findByTestId, findByRole } = render(
      <I18nextProvider i18n={i18n}>
        <InviteCollectEmails onSubmit={jest.fn()} />
      </I18nextProvider>,
      {
        query: {
          orgId: 666,
        },
      }
    );

    const submitBtn = await findByRole('button', {
      name: 'account:organization.invite.copyLink',
    });

    fireEvent.click(submitBtn);

    await findByTestId('loader');

    const alert …
Run Code Online (Sandbox Code Playgroud)

jestjs next.js react-i18next next-i18next

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

使用react-google-maps-api将自定义标记作为React组件

我们正在从 转变为google-map-react意味着react-google-maps-api更多原生 Google 地图 API 体验。

在更改之前,我们能够将自定义标记作为 React 组件加载,如下所示:

<GoogleMaps>
  <UserPinContainer lat={userLocation.lat} lng={userLocation.lng}>
    <Tidal.Icon type="UserLocation" text="User" />
  </UserPinContainer>
</GoogleMaps>
Run Code Online (Sandbox Code Playgroud)

从他们的原始 lib 文档中google-map-react,它说:

您可以在地图上渲染很酷的动画反应组件,而不是默认的 Google 地图标记、气球和其他地图组件。

虽然这很棒,但它证明了这个库已经脱离了原生 API...

然而,使用来自react-google-maps-api的新标记API ,React组件是不可能的。他们只期望string | google.maps.Icon | google.maps.Symbol;类型,例如:

<Marker
    icon={{
        path: google.maps.SymbolPath.CIRCLE,
        scale: 7,
    }}
    position={centers[0]}
/>
Run Code Online (Sandbox Code Playgroud)

或者

<Marker position={{ lat: userLocation.lat, lng: userLocation.lng }}>
    <Tidal.Icon img type="UserLocation" text="User" />
</Marker>
Run Code Online (Sandbox Code Playgroud)

我想我可以创建一个真正的自定义标记,例如:

const newMarker = new window.google.maps.Marker(MyComponent)
Run Code Online (Sandbox Code Playgroud)

但没有这样的运气。

对此有什么好的解决方案吗?

google-maps reactjs react-google-maps

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

在没有路由器或导航 uri 的情况下,将单页滚动反应为锚点

我很好奇设置这个非常简单的页面的内容结构。有一个导航/菜单栏,其中包含指向页面下方引用内容的锚点的链接。我不需要基于 react-router 的 URL 散列或历史跟踪。我不想在导航栏中有 DOM 查询,但我看到的问题是我当前的设置将这些组件作为兄弟组件,因此创建ref's 到组件意味着我必须创建一个笨拙的中间处理程序以在 2 之间传递它们地方。

主应用程序

const App = () => {
  return (
    <Provider store={store}>
      <div className="app">
        <Navibar />
        <Jumbo />
        <About /> // should have a ref
        <Projects />  // should have a ref
        <Contact />  // should have a ref
      </div>
    </Provider>
  );
};
Run Code Online (Sandbox Code Playgroud)

导航栏详细信息

handleClick = (e) => {
  window.scrollTo({
            top:this.myRef.current.offsetTop, 
            behavior: "smooth"
        })
}

<NavLink href="#about" onClick={this.handleClick}>About</NavLink>
Run Code Online (Sandbox Code Playgroud)

在主应用程序级别,我不需要将其设置为带有 props/state 的 Class,它应该只是一个功能组件。也许这是我的逻辑有缺陷的地方?但是,如果我让 App 组件接受 refCallbacks 并将它们传递给 Navibar,会解决它吗?

reactjs

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