我在测验应用中获取json数据时遇到了一些问题。
我已将json文件存储在与App.js和Running.js
相同的目录中我想展示问题和正确答案的选项。 所有这些都存储在quiz.json文件中。
Running.js文件:
import React,{Component} from 'react';
import {Collection,CollectionItem} from 'react-materialize';
class Running extends Component{
constructor(props){
super(props);
this.state={ques:1,score:0,isLoaded:false,items:[]};
}
componentDidMount() {
fetch("quiz.json")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.conversations
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render(){
console.log(this.state.items);
if(this.state.isLoaded){
return (
<div>
<h1 class="header center teal-text text-lighten-2">React Quiz</h1>
<br />
<Collection header={this.state.items[0]["question"]} >
{
this.state.items[0]["answers"].map(ans =>(<CollectionItem href='#'>{ans.value}</CollectionItem>))
}
</Collection>
</div>
)
}
else{
return <div>Not Rendered</div>
}
}
}
export default Running;
错误消息如下所示
TypeError: this.state.items is undefined
render
src/Running.js:37
34 | <div>
35 | <h1 class="header center teal-text text-lighten-2">React Quiz</h1>
36 | <br />
> 37 | <Collection header={this.state.items[0]["question"]} >
38 | {
39 | this.state.items[0]["answers"].map(ans =>(<CollectionItem href='#'>{ans.value}</CollectionItem>))
40 | }
json文件如下所示:
[
{
"question": "How can you access the state of a component from inside of a member function?",
"no": 1,
"answers": [
{
"key": 1,
"value": "this.getState()"
},
{
"key": 2,
"value": "this.prototype.stateValue"
},
{
"key": 3,
"value": "this.state"
},
{
"key": 4,
"value": "this.values"
}
]
},
{
"question": "Inline styling in React can be done as:",
"no": 2,
"answers": [
{
"key": 1,
"value": "style:{{}}"
},
{
"key": 2,
"value": "style:{}"
},
{
"key": 3,
"value": "style:''"
},
{
"key": 4,
"value": "All"
}
]
},
{
"question": "For classless component we use?",
"no": 3,
"answers": [
{
"key": 1,
"value": "functions"
},
{
"key": 2,
"value": "classes"
},
{
"key": 3,
"value": "JSX"
},
{
"key": 4,
"value": "None"
}
]
}
]