javascript - React - 如何创建链式级联辅助函数

标签 javascript reactjs ecmascript-6

如何在 React 中链接辅助方法?

我有一个带有辅助函数的 helper.js 文件。

即:(ps:下面只是暂时说明我的问题的普通方法)

//helper.js

export function handleLog(arg) {
  return console.log(`App current state is: ${arg}`);
}

export function handleSlice(arr) {
  return arr.slice(1, 2);
}

export function handleShuffle(arr) {
  return arr.sort(() => Math.random() - 0.5);
}

我可以将这些方法应用到我的 React 应用程序中:

import { handleLog, handleSlice, handleShuffle } from "./helpers";
...

class Heros extends PureComponent {
  constructor() {
    super();
    this.state = {
      heros: ["Hulk", "Thor", "Aquaman", "Stan Lee"]
    };
  }

  render() {
    const { heros } = this.state;
    const shuffledheros = handleShuffle(heros);
    const strongestHero = handleSlice(shuffledheros);
    handleLog(heros);

    /* How could I chain 👇 */
    // const strongestHero = handleShuffle(heros).handleSlice(heros);

    return (
      <>
        <h1>Chained Helpers</h1>
        Strongest: {strongestHero}
      </>
    );
  }
} 

我如何链接 ie: handleShuffle(heros).handleSlice(heros) 等等?

  • 当链接第二个方法时,它会抛出: (0 , _helpers.handleSlice)(...).handleSlice 不是函数

我没有成功地尝试将助手重构为:

const helpers = {
 f1() { ...do something...; return this;},
 f2() { ...do something...; return this;}
}
export default helpers

这也不起作用。这是完整的code

最佳答案

您可以创建一个自定义类,该类可以将数组作为内部属性来实现此目的:

class arrayUtils {
  constructor(items = []) {
    this._data = items;
  }
  reverseIt() {
    this._data.sort((a, b) => b - a)
    return this
  }
  getfirstTwo() {
    this._data.splice(0, 2)
    return this
  }
  printIt() {
    console.log('printing:', this._data)
    return this
  }
  get value() {
    return this._data
  }
}

// Create the instance
var arr = new arrayUtils([1, 2, 3, 4, 5])

// Chain subsequent calls (since we return `this`)
console.log('chain:', arr.reverseIt().printIt().getfirstTwo().printIt())

// get the value
console.log('value:', arr.value)

可以看到working here

特别是对于 React,您可以将其放在单独的 util 文件中的单独类中,然后简单地导出默认它:

class helpers ...

export default helpers

然后导入并创建一个实例:

import helper from './helper';

// Create the instance
var arr = new helper([1, 2, 3, 4, 5])

关于javascript - React - 如何创建链式级联辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53367430/

相关文章:

javascript - 图像映射中的背景图像

javascript - Prop 在控制台中工作,但不在前端渲染 - React

javascript - 无法访问从父级作为 props 传递的数组 - React

typescript - 用 ES6 和 Typescript 开 Jest

javascript - 处理对象操作数组

javascript - 获取 Uncaught ReferenceError : function is not defined

javascript - 使用从数据库检索的数据显示多个实时倒计时

javascript - 使用 useCallback Hook 内存 API 响应

javascript - 在React js中更新和对象嵌套数组

javascript - Angular 组件语法,在错误的上下文中调用的回调函数