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

javascript - How to console.log() this function? - Stack Overflow

programmeradmin1浏览0评论

I'd like to generate JSX for React-Native, yet I do want to examine each key/value using console.log().

what I am after:

{Object.keys(this.state.types).map((obj) => (
          console.log(obj); <-- This guy
          <Item label={obj[TYPE]} value={obj[ID]} />
          ))}

But an Error is thrown "Unexpected token"

How can I still debug my values inside map?

I'd like to generate JSX for React-Native, yet I do want to examine each key/value using console.log().

what I am after:

{Object.keys(this.state.types).map((obj) => (
          console.log(obj); <-- This guy
          <Item label={obj[TYPE]} value={obj[ID]} />
          ))}

But an Error is thrown "Unexpected token"

How can I still debug my values inside map?

Share Improve this question asked Jan 8, 2017 at 14:18 TedTed 3,87515 gold badges59 silver badges100 bronze badges 1
  • (obj) => ( That's not how you do an arrow function. – user2345 Commented Jan 8, 2017 at 14:22
Add a comment  | 

2 Answers 2

Reset to default 15

You can use the comma operator:

 {Object.keys(this.state.types).map((obj) => (
      console.log(obj), <-- This guy
      <Item label={obj[TYPE]} value={obj[ID]} />
      ))}

Which evaluates the statement and then discards it, or you can use the || operator which will evaluate console.log which returns false and then will return the React element:

 {Object.keys(this.state.types).map((obj) => console.log(obj) || (

      <Item label={obj[TYPE]} value={obj[ID]} />
      ))}

However, both are fairly hacky, I recommend you turn your arrow function into a multi-line arrow and just use return:

 {Object.keys(this.state.types).map((obj) => { 
      console.log(obj);
      return <Item label={obj[TYPE]} value={obj[ID]} />
  })}

On a side note - don't forget to set the key property on your objects returned from an array or you'll get a performance slowdown and a warning (you're currently not doing this).

The round brackets in => ( tell the function that it's returning an object (JSX is transpiled into a JS object). You want a function body to run console.log(), and then return the <Item> element.

Convert the round brackets to curly ones, and add a return statement:

{Object.keys(this.state.types).map((obj) => {
  console.log(obj); <-- This guy
  return (
    <Item label={obj[TYPE]} value={obj[ID]} />
  );
})}
发布评论

评论列表(0)

  1. 暂无评论