javascript Reactjs setState 箭头函数语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48003153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reactjs setState arrow function syntax
提问by Chandre Gowda
As per the React Docswe can have two ways for setState one with object syntax and other with function which they have shown as below
根据React Docs,我们可以有两种方法来设置 setState,一种使用对象语法,另一种使用函数,如下所示
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
My understanding of arrow functionsyntax is like () => {}where flower brackets are followed after arrow =>, but as per the sample it is round braces instead of flower brackets
我对箭头函数语法的理解就像() => {}箭头后面跟花括号一样=>,但根据示例,它是圆括号而不是花括号
What is the difference between these syntax ()=>{}and ()=>({}).
这些语法()=>{}和()=>({}).
Sample Code tried as per the docs which is working when this.setStage(prevStage=>({}))syntax is used in handleClickfunction, and if you change it to this.setState(prevStage=>{})it wont toggle the button value.
示例代码按照this.setStage(prevStage=>({}))在handleClick函数中使用语法时有效的文档进行尝试,如果您将其更改为this.setState(prevStage=>{})它不会切换按钮值。
Below is the working code:
下面是工作代码:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn : true
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : "OFF"}
</button>
</div>
);
}
}
采纳答案by Sagiv b.g
There are 2 main issues to consider here:
这里有两个主要问题需要考虑:
How arrow functionsworks?
What
setStateexpects when passingfunctionas a parameter?
Answers:
答案:
Arrow functions can return a value implicitly or explicitly.
When there is no function body (no curly brace{}) then you are returning implicitly:const x = () => 'we are returning a string here';When we use a function body, we need to use the
returnkey word:const x = () => { return 'another string returned' };There is another option to return something without the
returnkey word, you can wrap the curly brace with parentheses()and this will signal the engine that the curly brace are not a function body but an object, this is considered as creating an expression:const x = () => ({myKey: 'some string'});This is similar as we usually do with function expressions.
Especially with IIFE (Immediately Invoked Function Expression) :(function() { //some logic... })();If we will not return anything, then the function will just return
undefined.As for
setState, when you pass a function as a parameter, it expect that this function will return an object.
When your function didn't return anything (as stated above) it actually returnedundefined.
JavaScript won't yield an error as this is not an error. its just a function that returns nothing (undefined).
箭头函数可以隐式或显式返回一个值。
当没有函数体(没有大括号{})时,您将隐式返回:const x = () => 'we are returning a string here';当我们使用函数体时,我们需要使用
return关键字:const x = () => { return 'another string returned' };还有另一个选项可以返回不带
return关键字的内容,您可以用括号将花括号括起来(),这将向引擎发出信号,表明花括号不是函数体而是一个对象,这被视为创建一个表达式:const x = () => ({myKey: 'some string'});这与我们通常对函数表达式所做的类似。
特别是随着IIFE(我mmediately我nvoked ˚F结 Ë上的表达):(function() { //some logic... })();如果我们不返回任何东西,那么函数将只返回
undefined。至于
setState,当您将函数作为参数传递时,它期望该函数将返回一个对象。
当您的函数没有返回任何内容(如上所述)时,它实际上返回了undefined.
JavaScript 不会产生错误,因为这不是错误。它只是一个不返回任何内容的函数 (undefined)。
Here is a running example of your code without the wrapping parentheses:
以下是不带括号的代码的运行示例:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => {
return { // we must return an object for setState
isToggleOn: !prevState.isToggleOn
}
});
}
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : "OFF"}
</button>
</div>
);
}
}
ReactDOM.render(<Toggle />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Edit
As a followup to your comments
编辑
作为您评论的后续行动
I would expect Javascript to throw error when we return just key : value without enclosing parenthesis, i.e., () => {key:value} - which means it is trying to return 'key:value' and not Object, and this should be an JS error, but it did not throw any error. Please correct me if my understanding is wrong
当我们只返回 key : value 而不用括号括起来时,我希望 Javascript 会抛出错误,即 () => {key:value} - 这意味着它试图返回 'key:value' 而不是 Object,这应该是一个 JS 错误,但它没有抛出任何错误。如果我的理解有误请指正
It is not returning a key value, it is a "void" function that returns undefined.
See this running snippet:
它不返回键值,它是一个返回undefined.
看到这个正在运行的片段:
const x = () => {myKey: 'myValue'};
const y = x();
console.log(y);
Edit#2
Followup to your other comments (which is basically kind of a whole different question in my opinion).
编辑#2
跟进您的其他评论(在我看来,这基本上是一个完全不同的问题)。
let y = function() {'abc':1} - syntax error, let y = function(){abc:1} and let y = function(){ return {'abc':1} } - no error, where first one (syntax error) we are trying to assign 1 to string abc, which is same as 3rd sample (no error), and 2nd example assigning 1 to abc - works when there is no quotes. Please explain the difference of these 3 samples and why 1st one fails and not 2nd example
let y = function() {'abc':1} - 语法错误, let y = function(){abc:1} 和 let y = function(){ return {'abc':1} } - 没有错误,其中第一个(语法错误)我们试图将 1 分配给字符串 abc,这与第三个样本(无错误)相同,第二个示例将 1 分配给 abc - 在没有引号时有效。请解释这 3 个样本的区别以及为什么第一个失败而不是第二个示例
OK, this is getting interesting.
好的,这变得有趣了。
where first one (syntax error) we are trying to assign 1 to string abc...
其中第一个(语法错误)我们试图将 1 分配给字符串 abc ...
No we are not.
We are trying to create a label:, but labels can'tbe strings!
Same as variables can'tbe strings - var 'x' = 1.
不,我们不是。
我们正在尝试创建一个label:,但标签不能是字符串!
与变量不能是字符串相同 - var 'x' = 1。
This is a valid syntax in JavaScript:
这是 JavaScript 中的有效语法:
const y = function(){b:2};
What we are doing here is creating a label:named aand this label has an expression of 1(we are not doing anything with this label.).
我们在这里所做的是创建一个label:命名的a并且这个标签有一个表达式1(我们没有对这个标签做任何事情。)。
const x = () => {a:1};
const y = function(){a:1};
This syntax is invalid:
此语法无效:
const y = function() { 'a': 1 };
This is not valid because labels can't start with a string:
这是无效的,因为标签不能以字符串开头:
const x = () => { 'a': 1 };
const y = function() { 'a': 1 };
And again, this is not a key:valuepair, the curly brace are the function's BODY.
再说一次,这不是一key:value对,花括号是函数的BODY。
回答by Chandre Gowda
Later I referred MDNand found details under Advanced Syntax section, that if you want to return objects implicitly then we need to enclose it within () , that answered my question.
后来我参考了MDN并在高级语法部分找到了详细信息,如果你想隐式返回对象,那么我们需要将它包含在 () 中,这回答了我的问题。
// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
// 给函数体加上括号以返回一个对象字面量表达式:
参数 => ({foo: bar})
回答by MBehtemam
the simple answer is
简单的答案是
()=>({})
also it's equal to
也等于
()=> {
return {}
}
return an empty object,here parentheses around {}mean return. also you know we must pass object to setStateso we insert any thing we want to state between {}
返回一个空对象,这里{}是 mean周围的括号return。你也知道我们必须将对象传递给setState所以我们插入任何我们想要声明的东西{}
()=>({any thing you want to set to state})
回答by Fralle
If you only write () => {} this explicitally means that the function does more than just return something.
如果你只写 () => {} 这明确意味着该函数不仅仅是返回一些东西。
For example:
例如:
const logAndReturn = (val) => {
console.log(val)
return val
}
But let's say you have a function that takes params and returns an object based on those params.
但是假设您有一个函数,它接受参数并根据这些参数返回一个对象。
const createUser = (x) => {
prop: x
}
This will prompt an error, cause this basically translates to:
这将提示一个错误,因为这基本上转化为:
function createUser(x) {
prop:x
}
With paranthesis you are still using the default return from the arrow function.
使用括号,您仍然使用箭头函数的默认返回值。
const createUser = (name, email) => ({})
function createUser(name, email) { return {} )

