Javascript我可以将const转换为输出功能吗

时间:2019-03-19 08:50:42

标签: 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新手。 谢谢。

4 个答案:

答案 0 :(得分:2)

第二个代码段使用“回调”模式,通常仅在函数本身是 asynchronous 时使用(即,它不会立即返回结果,而是必须去做一些背景工作)工作,然后最终返回该结果。)

因此,只有在所讨论的特定API支持该模式时,它才有效。

如果只想避免分配给变量,请执行以下操作:

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

答案 1 :(得分:0)

只需更改变量定义:

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

答案 2 :(得分:0)

是的,但是您需要更改getFieldValue函数定义以接受回调并为您运行。 您的getFieldValue函数应定义为:

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

答案 3 :(得分:0)

如果要在使用值之前先对其进行操作,但无法在JSX中声明一个const,则定义一个函数来对其进行操作。这很简单明了:

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

render() {
    return <div>
        { this.doSomethingWithGender(this.props.form.getFieldValue('product_gender')) }
    </div>
}