Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 反应:简写更新状态变量_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript 反应:简写更新状态变量

Javascript 反应:简写更新状态变量,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,在React中,为了处理变量更改,我们执行以下操作: handleChangeRound = (round) => { this.setState({round: round}); } updateLoading = (isLoading) => { this.setState({isLoading: isLoading}); } 有写作的方法吗 this.setState({round: round}); this.setState({isLoading: isLoad

在React中,为了处理变量更改,我们执行以下操作:

handleChangeRound = (round) => {
  this.setState({round: round});
}

updateLoading = (isLoading) => {
  this.setState({isLoading: isLoading});
}
有写作的方法吗

this.setState({round: round});
this.setState({isLoading: isLoading});
作为

给定状态中存在变量
round
isLoading
,并与变量名称相对应,以避免冗余
变量:variable


PS:灵感来自:

console.log({x: x, y: y});
// output:
// {x: 10, y:20}
可以写成

console.log({x,y});
// output:
// {x: 10, y:20}
你可以这样写

this.setState({round});
this.setState({isLoading}); 
通过使用ECMAScript 6/ES2015中的对象属性速记。基本上,这背后的想法是,您可以省略属性键,因为变量声明具有该键


您只需使用动态对象编写setState,并将对象传递给函数,如

this.updateState({ round });
this.updateState({ isLoading });

updateState = (obj) => {
   this.setState(obj)
}

您可以将setState与回调一起使用

this.setState(prevState => {
 return {
   isLoading:!prevState.isLoading
 }
})

或者你可以从prevState做任何事情

我假设你误解了这个问题。@murat karagöz所以这个语法
{variable}
适用于出现模式
{variable:variable}
的任何地方?我的意思是,它是ES6规范还是什么?@SaravanabalagiRamachandran是的,新的Ecmascript可以实现。我们叫它什么:它有具体的名称吗?另外,如果你能用它的通用适用性来更新答案,那就太好了,这样对其他人也会有用:)@SaravanabalagiRamachandran更新了答案。创建一个看起来完全相同的附加方法,你会得到什么好处?@TimCastelijns,这可以用作通用方法,而不是使用不同的方法,如
handlechangeand
updateload
this.setState(prevState => {
 return {
   isLoading:!prevState.isLoading
 }
})