反应解析错误:意外的令牌,预期为“;”

时间:2020-09-28 09:31:37

标签: reactjs

我正在从一个名为jokesData.js的文件读取一个数组,如下所示,位于App.js文件中。如果我在render(){}中添加返回({jokeComponents}),则会收到以下错误。我们是否不需要render()

enter image description here

const jokesData = [
    {
        id: 1,
        punchLine: "It’s hard to explain puns to kleptomaniacs because they always take things literally."
    },
    {
        id: 2,
        question: "What's the best thing about Switzerland?",
        punchLine: "I don't know, but the flag is a big plus!"
    },
    {
        id: 3,
        question: "Did you hear about the mathematician who's afraid of negative numbers?",
        punchLine: "He'll stop at nothing to avoid them!"
    }
]

export default jokesData

import React from 'react';
import './App.css';
import Joke from './components/Joke.js';
import jokesData from './data/jokesData.js'

function App() {

  const jokeComponents = jokesData.map((joke) => <Joke key={joke.id} question={joke.question} punchLine = {joke.punchLine} />)

    
    render() {
      return (
        <div>
          {jokeComponents}
        </div>
      )
    }

}

export default App

3 个答案:

答案 0 :(得分:2)

render()是类组件所必需的。

尝试下面的代码。

import React from 'react';
import './App.css';
import Joke from './components/Joke.js';
import jokesData from './data/jokesData.js'

function App() {

  const jokeComponents = jokesData.map((joke) => <Joke key={joke.id} question={joke.question} punchLine = {joke.punchLine} />)

       return (
        <div>
          {jokeComponents}
        </div>
      );

}

export default App

答案 1 :(得分:1)

只需返回您的jsx即可。您不需要功能组件中的任何渲染功能

 return (
        <div>
          {jokeComponents}
        </div>
      );

答案 2 :(得分:0)

render函数仅适用于类组件。您无需在功能组件中编写它。

import React from 'react';
import './App.css';
import Joke from './components/Joke.js';
import jokesData from './data/jokesData.js'

function App() {

  const jokeComponents = jokesData.map((joke) => <Joke key={joke.id} question={joke.question} punchLine = {joke.punchLine} />)
  
  return (
    <div>
      {jokeComponents}
    </div>
  )
    
}

export default App

相关问题