我在将数据从JSON文件传递到我尝试创建的测验组件时遇到问题。到目前为止,我很幸运通过我存储在Src文件夹中的简单JSON文件传递数据。但是,当我尝试访问位于公用文件夹中的更大文件时,什么也不会返回。而不是返回填充有“当前问题”和“当前选项”的对象,它返回一个空白对象。
如果应用程序显示某种错误,这会有所帮助,但是由于我不知道是什么原因导致的,所以我现在很茫然。
这是用于生成问题的主文件,我利用此组件从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文件的片段,用于获取测验信息(目前非常基本)
"questions": [
{
"question": "How tall is your fridge?",
"options": [
{
"option": "6 feet"
},
{
"option": "12 feet"
},
{
"option": "3 feet"
},
{
"option": "1 foot"
}
]
}
谢谢,感谢您的帮助!
我认为问题在于道具在通过之前需要花费一些时间来加载。因此,您应该尝试使用componentDidupdate而不是componentDidMount,以便在道具更新数据时可以使用它。
我不确定下面的代码是否会起作用,请尝试一下以适应您的喜好。
class Play extends React.Component {
constructor(props){
super(props);
this.state = {
questions: [],
currentQuestion: {},
nextQuestion: {},
previousQuestion: {},
answer: "",
currentQuestionIndex: 0,
initComplete: false
}
}
componentDidUpdate(){
const {questions} = this.props;
if(!IsEmpty(questions) && !initComplete){
currentQuestion = questions[currentQuestionIndex];
nextQuestion = questions[currentQuestionIndex + 1];
previousQuestion = questions[currentQuestionIndex - 1];
const answer = currentQuestion.answer;
this.setState({
questions,
currentQuestion,
nextQuestion,
previousQuestion,
answer,
initComplete = true
});
}
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>
)
}
}