Javascript我可以将const转换为具有输出的函数吗

Javascript我可以将const转换为具有输出的函数吗,javascript,function,ecmascript-6,Javascript,Function,Ecmascript 6,我现在正在学习javascript,我在工作时有了一个想法,我能改变这个吗: const x = this.props.form.getFieldValue('product_gender') console.log(x) 变成类似于: this.props.form.getFieldValue('product_gender', x => console.log(x)) 如果听起来很愚蠢,请原谅我,但我是javascript新手。 谢谢。只需实际更改变量定义: const x = t

我现在正在学习javascript,我在工作时有了一个想法,我能改变这个吗:

const x = this.props.form.getFieldValue('product_gender')
console.log(x)
变成类似于:

this.props.form.getFieldValue('product_gender', x => console.log(x))
如果听起来很愚蠢,请原谅我,但我是javascript新手。
谢谢。

只需实际更改变量定义:

const x = this.props.form.getFieldValue('product_gender', x => console.log(x));

第二个代码段使用“回调”模式,通常仅在函数本身是异步的情况下使用(即,它不会立即返回其结果,而是必须进行一些后台工作,然后最终返回该结果)

因此,只有当所讨论的特定API支持该模式时,它才起作用

如果您只是想避免赋值给变量,只需执行以下操作:

console.log(this.props.form.getFieldValue('product_gender'));

可以,但您需要更改
getFieldValue
函数定义以接受回调并运行它。 您的
getFieldValue
函数的定义如下:

function getFieldValue(productName, callback){
  // do something with the productName
  const returnValue = calculateYourReturnValue()
  // call the callback function
  callback(returnValue)
  return returnValue
}

如果您想在使用值之前对其进行操作,但无法在JSX中声明常量,那么请定义一个函数对其进行操作。这是简单明了的:

doSomethingWithGender(gender) {
    return gender + "some extra text";
}

render() {
    return <div>
        { this.doSomethingWithGender(this.props.form.getFieldValue('product_gender')) }
    </div>
}
doSomethingWithGender(性别){
返回性别+“一些额外文本”;
}
render(){
回来
{this.doSomethingWithGender(this.props.form.getFieldValue('product_gender'))}
}

您的问题不清楚。请告诉我您希望发生什么?@MaheerAli我希望能够在不分配
const
的情况下直接操作值您需要更改getFieldValue的实现方式在这种情况下
直接操作值
哪个值?我不想声明
const
@SimpleWebDesigner,但您刚才在请评论我的回答,您确实需要变量。所以您只需要运行
this.props.form.getFieldValue
函数?这也是我的建议,但显然不是OP想要的。这个问题目前还不清楚我在寻找什么,但我理解需要更改
this.props.form.getFieldValue
@SimpleWebDesigner的结构的概念,那么你在寻找什么呢?为什么你认为你想要(或需要)使用这种模式?除非您的
getFieldValue
函数是异步的,否则它不会提供任何好处。@Alnitak因为有时我无法在react中的JSX中声明
const
,所以我只想找到一种方法来获取该值。@SimpleWebDesigner并使用该值做什么?这听起来好像你问错了问题,需要问一个新的问题,在React的上下文中说明这一点。另见“XY问题”。