Javascript React-如何创建链式级联辅助函数
如何在React中链接帮助器方法 我有一个带有helper函数的Javascript React-如何创建链式级联辅助函数,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,如何在React中链接帮助器方法 我有一个带有helper函数的helper.js文件 ie:(附言:下面是一些普通的方法来说明我目前的问题) 我可以将这些方法应用于我的React应用程序,如下所示: import { handleLog, handleSlice, handleShuffle } from "./helpers"; ... class Heros extends PureComponent { constructor() { super(); this.s
helper.js
文件
ie:(附言:下面是一些普通的方法来说明我目前的问题)
我可以将这些方法应用于我的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 First: Array.sort doesn't return any array.
You should rewrite your function handleShuffle
export function handleShuffle(arr) {
return arr.concat().sort(() => Math.random() - 0.5);
}
import{handleLog,handleSlice,handleShuffle}来自“/helpers”;
...
类Heros扩展了PureComponent{
构造函数(){
超级();
此.state={
英雄:[“绿巨人”、“雷神”、“水瓶人”、“斯坦·李”]
};
}
render(){
const{heros}=this.state;
const shuffledheros=handleShuffle(heros);
const strongestHero=手虱(洗牌英雄);
汉德莱洛(英雄);
/*我怎样才能先链接:不返回任何数组
您应该重写函数handleShuffle
const strongestHero = handleShuffle(handleSlice(heros));
第二:您尝试调用数组函数,但array
不包含任何handleShuffle
或handlessplice
函数。因此,您应该逐个函数运行函数:
Array.prototype.handleSlice = function() {
return this.slice(1, 2);
};
Array.prototype.handleShuffle = function() {
return this.concat().sort(() => Math.random() - 0.5);
};
另一个解决方案:创建阵列原型的方法:
heros.handleShuffle().handleSlice();
因此,您可以将方法作为级联执行
但我认为为这些简单函数扩展数组并不是最好的主意。您可以创建一个自定义类,该类可以将数组作为内部属性来保存,以实现以下目的:
类数组直到{
构造函数(项=[]){
这是。_数据=项目;
}
反转(){
这个._data.sort((a,b)=>b-a)
还这个
}
getfirstTwo(){
此._数据拼接(0,2)
还这个
}
printIt(){
console.log('printing:',this.\u数据)
还这个
}
获取值(){
返回此数据。\u
}
}
//创建实例
var arr=新的阵列单元([1,2,3,4,5])
//链接后续调用(因为我们返回'this`)
console.log('chain:',arr.reverseIt().printIt().getfirstTwo().printIt())
//获取值
console.log('value:',arr.value)
提供的fork不执行handleShuffle
只执行handleShuffle
。我也不明白为什么需要concat
?我的洗牌方法很有效,我只是无法将它们链接在一起。我们需要concat,因为sort
函数不返回任何内容。我给出了解释handleShuffle>的链接(手虱(英雄))
我一步一步地执行了两个函数问题是你的建议不是对数组进行洗牌。它只会在每个页面重新加载时返回相同的值。因为我是先切片数组,然后用1个元素洗牌数组。你能告诉我这种方法会如何反应吗?当然,请参阅附件中的答案链接谢谢!这对我来说很有趣,也是一个全新的领域。我对OOP范例还很陌生。
heros.handleShuffle().handleSlice();