我在so called curried format中有以下箭头功能,取自this SO answer:
BigInteger
我需要在用ES6语法编写的React组件中使用它,由于the implementation而无法处理ES7属性初始值设定项。
"通常" React中的类上下文中的函数具有以下简单样式:
const getIntervals = n=> availability=> {}
但我会将myFunction () {}
函数转换为此样式吗?
答案 0 :(得分:3)
只需将getIntervals
定义为常规方法,但让它返回你的curried函数:
class Example extends Component {
getIntervals(n) {
return (availability) => {
}
}
render() {...}
}
答案 1 :(得分:1)
很酷,看到我的作品在另一个问题中被引用。我很高兴它能帮到你。
@RobM为你提供了一个(通常的)好的答案,但我会给你另一种选择。
首先,没有必要将函数保持为curried格式。由于这是一个用户定义的过程,如果它最好让你有一个元组,你可以这样做!转换它就像......†
一样简单// curried form
const getIntervals = n=> availability=> { ... }
// uncurried form
const getIntervals = (n,availability)=> { ... }
然后当你打电话时
// curried form
getIntervals (30) (availability)
// changes to
getIntervals(30, availability)
我通常以咖喱形式定义函数,但这绝不是您必须遵循的要求。在未经处理的形式中,您可以直接在React组件上定义它,就像这样......
class Example extends Component
getIntervals (n,availability) {
// ...
}
}
或者因为getIntervals
是一个通用的纯函数,所以没有理由将其所有代码嵌入到组件中。您可以轻松地将其完全分开
// curried
const getIntervals = n=> availability=> { ... }
// or choose uncurried
const getIntervals = (n,availability)=> { ... }
// call it from withint the class
class Example extends Component
getIntervals (availability) {
return getIntervals (this.props.intervalLength, availability)
}
}
或者,现在你可能会看到拥有一个包装函数是多么无用。返回值更有可能以某种其他方式使用,例如在事件处理程序或某些状态变异中......
const getIntervals = (n,availability) => { ... }
class Example extends Component {
// constructor ...
onclick (event) {
let intervals = getIntervals(this.props.intervalLength, this.state.availability)
// do something with intervals
console.log(intervals)
}
render () {
return <button onClick={e=> onclick(e)}>show intervals</button>
}
}
如果您愿意,现在getIntervals
可以完全保留此文件。您可以将其放在 utils.js 中并导入
import {getIntervals} from './utils'
class Example extends Component {
onclick (event) {
let intervals = getIntervals(this.props.intervalLength, this.state.availability)
// ...
}
// ...
}
我使用this.props.intervalLength
和this.state.availability
作为示例。我实际上并不知道这两个值是如何与组件相关联的。我把它留给你^ _ ^
†从curried到uncurried过程的转换通常很简单,但是如果curried过程是递归过程,你必须要小心 - 在这种情况下,你还必须更新递归调用,使其处于未经处理的状态同样。
我将此作为脚注留下,因为我写了getIntervals
并且在这种特定情况下转换很简单