下面的代码来自React Native Docs。正如您所看到的,有两个带有胖箭头的函数解密。我理解在包含.... previousState => ({等内容的行中使用普通括号的用法。这里需要使用(),因为它返回一个object文本。但是,我不明白为什么我们要在setInterval的回调函数中使用"(“。我指的是这一行:setInterval(() => ( ...。为什么我们不像setInterval(() => { .....那样写
class Blink extends Component {
componentDidMount() {
//HEART OF THE QUESTION. Why do we use "(" below, instead "{". Do we need to return for setInterval or just define a function to run ?
setInterval(() => (
//Here, "(" is normal because it returns object literal
this.setState(previousState => ({
isShowingText: !previousState.isShowingText
}))
), 1000);
}
//....
}
发布于 2019-10-28 23:09:01
setInterval不需要退货。这两种方法都可以很好地工作:
setInterval(() =>
this.setState(previousState => ({
counter: previousState.counter + 1 || 1
})),
1000);还有这个(在我看来,没有括号就不好了):
setInterval(() => {
this.setState(previousState => ({
counter: previousState.counter + 1 || 1
}));
}, 1000);通常,多行返回需要使用括号,下面是一个很好的解释:http://jamesknelson.com/javascript-return-parenthesis/
https://stackoverflow.com/questions/58592517
复制相似问题