javascript - How setState with one value work? - Stack Overflow

I was looking through some code while using the npm package React-SelectInterestingly enough i saw setS

I was looking through some code while using the npm package React-Select

Interestingly enough i saw setState being used as such:

handleSelectChange (value) {
        console.log('You\'ve selected:', value);
        this.setState({ value });
    },

How does setState work like this? It only provides one value? I am asking because I would like to perhaps capture one thing from my input and then change it. But that doesn't work as intended.

handleSelectChange (value) {
        console.log('You\'ve selected:', value);
        this.setState({ value.name });
    },

The full code is here, its fairly short: .js

I was looking through some code while using the npm package React-Select

Interestingly enough i saw setState being used as such:

handleSelectChange (value) {
        console.log('You\'ve selected:', value);
        this.setState({ value });
    },

How does setState work like this? It only provides one value? I am asking because I would like to perhaps capture one thing from my input and then change it. But that doesn't work as intended.

handleSelectChange (value) {
        console.log('You\'ve selected:', value);
        this.setState({ value.name });
    },

The full code is here, its fairly short: https://github./JedWatson/react-select/blob/master/examples/src/ponents/Multiselect.js

Share Improve this question asked Jul 6, 2016 at 23:24 ApathyBearApathyBear 9,62515 gold badges59 silver badges90 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

When using in ES6

this.setState({ value })

It is just a shorthand for

this.setState({ value: value })

There's nothing else magical happening here


For more clarity, consider this example

var x = 5
var y = 10
var z = { x, y }
console.log(z)
//=> { x: 5, y: 10 }


If you want to set the state to value.name you would not be able to use the shorthand if the key you had to set was still called value

this.setState({ value: value.name })

This is a ES2015 feature, the property name shorthand. It saves you from typing the name of the key when you are assigning it the value of a variable of the same name.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744269863a4566047.html

相关推荐

  • javascript - How setState with one value work? - Stack Overflow

    I was looking through some code while using the npm package React-SelectInterestingly enough i saw setS

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信