最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React elements and fat arrow functions - Stack Overflow

programmeradmin2浏览0评论

In the Redux examples, the syntax used is:

const App = () => (
  <div>
    <AddTodo />
    <VisibleTodoList />
    <Footer />
  </div>
)

I was toying around with a new example app and mistyped the above code with curly brackets instead of parentheses like so:

const App = () => {
  <div>
    <AddTodo />
    <VisibleTodoList />
    <Footer />
  </div>
}

I console logged both of the following and the result seemed to be the same. My question is what is the difference between these 2 and why does React like the parentheses but not the curly brackets?

In the Redux examples, the syntax used is:

const App = () => (
  <div>
    <AddTodo />
    <VisibleTodoList />
    <Footer />
  </div>
)

I was toying around with a new example app and mistyped the above code with curly brackets instead of parentheses like so:

const App = () => {
  <div>
    <AddTodo />
    <VisibleTodoList />
    <Footer />
  </div>
}

I console logged both of the following and the result seemed to be the same. My question is what is the difference between these 2 and why does React like the parentheses but not the curly brackets?

Share Improve this question asked Mar 11, 2016 at 1:35 MCawMCaw 2373 silver badges11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 23

TL;DR

Your first example is more or less equivalent to:

var App = function() { return <div>...</div>; };

Your second is more or less equivalent to:

var App = function() { <div>...</div>; };

React is probably complaining that nothing is being returned in the second example.

Slightly Longer Version

Let's take React out of the equation. In es6 you can create a fat arrow function like this:

const getWord = () => {
  return 'unicorn';
}

And we're given a shortcut to do the same thing with less code:

const getWord = () => 'unicorn';

unicorn is returned even though you don't ever explicitly type return anywhere.

In your first example, you wrapped your JSX in parenthesis. The equivalent in our simple example is:

const getWord = () => ('unicorn');

or this

const getWord = () => (
  'unicorn'
);

The last four examples are equivalent. Hope that helps!

发布评论

评论列表(0)

  1. 暂无评论