【发布时间】:2020-08-06 22:17:25
【问题描述】:
我在将数据从我的 JSON 文件传递到我尝试创建的测验组件时遇到问题。到目前为止,我有幸通过一个简单的 JSON 文件传递数据,该文件存储在我的 Src 文件夹中。但是,当我尝试访问位于我的公用文件夹中的更大文件时,没有返回任何内容。它不是返回一个填充了“当前问题”和“当前选项”的对象,而是返回一个空白对象。
如果应用程序显示某种错误会更有帮助,但因为我不知道是什么原因造成的,所以我现在不知所措。
这是用于生成问题的主文件,我利用这个组件从我的 JSON 文件中传递属性。
class Play extends React.Component {
constructor(props){
super(props);
this.state = {
questions: this.props.questions,
currentQuestion: {},
nextQuestion: {},
previousQuestion: {},
answer: "",
currentQuestionIndex: 0,
}
}
componentDidMount(){
const {questions, currentQuestion, nextQuestion, previousQuestion} = this.state;
this.displayQuestions(questions,currentQuestion, nextQuestion,previousQuestion)
}
displayQuestions = (questions = this.state.questions, currentQuestion, nextQuestion, previousQuestion) => {
let { currentQuestionIndex } = this.state;
if(!IsEmpty(this.state.questions)){
questions = this.state.questions;
currentQuestion = questions[currentQuestionIndex];
nextQuestion = questions[currentQuestionIndex + 1];
previousQuestion = questions[currentQuestionIndex - 1];
const answer = currentQuestion.answer;
this.setState({
currentQuestion,
nextQuestion,
previousQuestion,
answer
});
}
}
render(){
const {currentQuestion} = this.state;
return(
<React.Fragment>
<Container>
<H5> {currentQuestion.question}</H5>
<OptionsContainer>
<ul>
{!!currentQuestion.options && currentQuestion.options.map((option) =>
<p className = "option"> {option.option}</p>
)}
</ul>
</OptionsContainer>
</Container>
</React.Fragment>
)
}
}
这就是我使用 Play 组件从下面的 JSON 文件中动态传递数据的方式。
<Play questions = {this.props.questions}/>
这是从动态呈现 url 并将每组数据放在单独的组件中的组件的片段。
<Route path = {`${url}/:topicId`} render = {
({ match }) =>
<TopicHeaderCard {...coreTopics.find(topic => topic.id === match.params.topicId)}/>}
/>
我的 JSON 文件的 sn-p 用于获取测验信息(目前非常基本)
"questions": [
{
"question": "How tall is your fridge?",
"options": [
{
"option": "6 feet"
},
{
"option": "12 feet"
},
{
"option": "3 feet"
},
{
"option": "1 foot"
}
]
}
在此先感谢,感谢所有帮助!
【问题讨论】:
标签: json reactjs object react-router components