【发布时间】:2020-04-13 02:20:08
【问题描述】:
我正在尝试创建一个笑话应用程序,它显示我本地 json 文件中的一个随机笑话。现在显示的问题和妙语不匹配。我尝试使用 id 以使问题和答案都出现,<h1{this.getRandomJoke().answer}</h1>,但分配给该 id 的数字出现了。我怎样才能使它起作用,以便问题和妙语匹配?
这就是我的本地 json 文件的设置方式:
const SportsJokesData = [
{
id: "1",
question: "What did the baseball glove say to the ball?",
answer: "Catch ya later!"
}
]
export default SportsJokesData;
这就是我的方式
import React from 'react'
import SportsJokesData from './SportsJokesData';
class SportsJokesApi extends React.Component {
getRandomJoke(){
return SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
}
render() {
return (
<React.Fragment>
<p>{this.getRandomJoke().question}</p>,
<h1>{this.getRandomJoke().answer}</h1>
</React.Fragment>
)
}
}
export default SportsJokesApi;
【问题讨论】:
-
只是让您知道您调用 JSON 的文件实际上不是 JSON 格式。你所拥有的是一个模块化的 Javascript 文件,它使用数组和对象文字表示法。它与 JSON 类似但不一样,例如 JSON 需要
"s 围绕对象属性名称。
标签: javascript json reactjs