javascript - 在 React.js 中创建可重用的辅助函数

标签 javascript reactjs redux

我一直在为我最新的应用程序构建 React 组件。我知道我可以重用组件,这有助于保持我的代码干燥。

我想知道是否可以重用函数。我知道一定有办法。

现在我有三个使用密码验证功能的组件。

passwordValidation() {
  const length = this.state.password.length;
  if (length > 7) return 'success';
  else if (length > 4) return 'warning';
  else if (length > 0) return 'error';
}

我创建了一个帮助程序文件 - helpers.jsx 并添加了:

export function passwordValidation() {
  const length = this.state.password.length;
  if (length > 7) return 'success';
  else if (length > 4) return 'warning';
  else if (length > 0) return 'error';
}

然后我将其导入到我的组件中

import { passwordValidation } from '../helpers.jsx'

当我尝试在构造函数中绑定(bind)“this”时,我不断收到错误“passwordValidation 不是函数”。

如果我在输入标记中调用它,我会收到“无法读取未定义的属性状态。”

只是想看看我哪里出了问题。如果我在类中定义它并添加 this.passwordValidation = this.passwordValidation.bind(this),则一切正常。

如果这不是最佳实践,我会回到我正在做的事情,但我假设我应该能够导入函数以使生活更轻松并使我的代码更干净!

最佳答案

辅助函数不应该依赖于它们被调用的组件的上下文(至少在我看来)。如果您需要在函数中使用某些参数,则将其传递给函数始终是更好的做法,因为它有助于可重用性。所有组件的状态属性键可能都不同,如果您忘记为状态属性使用准确的键,则可能会导致错误。

例如

export function passwordValidation(password) {
  const length = password.length;
  if (length > 7) return 'success';
  else if (length > 4) return 'warning';
  else if (length > 0) return 'error';
}

如果我像上面那样更改函数,我可以使用下面所有给定的示例。

import { passwordValidation } from '/path/to/helper/functions.js';

console.log(passwordValidation(this.state.password));
console.log(passwordValidation(this.state.confirmPassword));
console.log(passwordValidation(this.props.password));
console.log(passwordValidation(someFetchedObject.user.password));

关于javascript - 在 React.js 中创建可重用的辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46838854/

相关文章:

reactjs - 如何在不提交的情况下访问formik字段的当前值?

reactjs - 类型错误 : Cannot read property 'map' of undefined"React

reactjs - 为什么我需要 redux async thunk

javascript - 从鼠标位置获取 map 经纬度

javascript - 从 Javascript 更改媒体特定的 CSS 属性

javascript - 如何将确认对话框添加到 html5 表单的提交按钮?

reactjs - 如何使用 immer.js 更新多个状态属性

javascript - IE 中隐藏元素导致表单提交

reactjs - 为什么我在 Mapbox GL 中设置了我的数据集要素 ID 却未定义它们?

javascript - 在 React Apollo 查询返回后调度 Redux 操作