React:JSX中的三元操作产生“意外令牌”错误

时间:2018-03-29 04:50:36

标签: reactjs ternary-operator

我想在开始显示之前检查数组是否为空。这是我的代码:

{ item2.user.entities.url !== null 
              ? ({item2.user.entities.url.urls.map((item3,index3) => {
                    return(
                        <a href={item3.expanded_url} target='_blank'>{item3.expanded_url}</a>
                      )
                    })
                  })
              : null
            }

我不确定。显示错误

babel.min.js:8 Uncaught SyntaxError: Inline Babel script: Unexpected token, expected , (187:23) 
  186 |           { item2.user.entities.url !== null 
> 187 |               ? ({item2.user.entities.url.urls.map((item3,index3) => {
      |                        ^
  188 |                     return(
  189 |                         <a href={item3.expanded_url} target='_blank'>{item3.expanded_url}</a>
  190 |                       )
    at t.le.raise (babel.min.js:8)
    at t.Z.unexpected (babel.min.js:7)
    at t.Z.expect (babel.min.js:7)
    at t.se.parseObj (babel.min.js:8)
    at t.se.parseExprAtom (babel.min.js:8)
    at t.parseExprAtom (babel.min.js:9)
    at t.se.parseExprSubscripts (babel.min.js:8)
    at t.se.parseMaybeUnary (babel.min.js:7)
    at t.se.parseExprOps (babel.min.js:7)
    at t.se.parseMaybeConditional (babel.min.js:7)

无法理解错误是什么

2 个答案:

答案 0 :(得分:2)

您有额外的{}

const a = item2 => {
  item2.user.entities.url !== null
    ? item2.user.entities.url.urls.map((item3, index3) => {
        return (
          <a href={item3.expanded_url} target="_blank">
            {item3.expanded_url}
          </a>
        );
      })
    : null;
};

答案 1 :(得分:1)

你不能在另一个JSX表达式中有一个JSX表达式({})。

您需要使用类似<div>的元素包装第二个JSX表达式:

{item2.user.entities.url !== null ? (
    <div>
        {item2.user.entities.url.urls.map((item3, index3) => (
            <a href={item3.expanded_url} target='_blank'> 
                {item3.expanded_url}
            </a>
        )}
    </div>
 ) : null}

或者将它作为单个表达式:

{item2.user.entities.url !== null ? item2.user.entities.url.urls.map((item3, index3) => (
    <a href={item3.expanded_url} target='_blank'> 
        {item3.expanded_url}
    </a>
 ) : null}