reactjs - 反应:无法替换渲染()方法中的组件
问题描述
我正在为练习构建一个简单的问答游戏,但是在问题更改方面存在一些问题。我计划一一处理渲染问题的方式是在数组中创建一个问题队列作为组件状态(PractiseScreen.prototype.state.questionQueue),并使用 IntermediateRenderer 组件将当前问题索引作为道具和问题传递按原样排队,因此它可以在父组件的状态更改上呈现正确的问题。但是,当我调试组件时,我没有看到下一个问题被呈现。
我的代码有什么问题?提前致谢!
import React from 'react';
import * as Animatable from 'react-native-animatable';
import {
View,
Text,
StatusBar,
TouchableWithoutFeedback,
} from 'react-native';
import MyText from '../custom-components/MyText';
import Question from '../components/Question';
import entries from '../mockData/entries';
class IntermediateRenderer extends React.Component {
render() {
return (<React.Fragment>
{this.props.allQuestionComponents[this.props.questionIndexToRenderNext]}
</React.Fragment>)
}
}
export default class PractiseScreen extends React.Component {
static navigationOptions = {
header: null
}
constructor() {
super();
this.state = {
currentQuestionIndex: 0,
questionQueue: []
}
this.buildQuestionQueue = this.buildQuestionQueue.bind(this);
this.goToNextQuestion = this.goToNextQuestion.bind(this);
}
componentDidMount() {
this.buildQuestionQueue();
}
buildQuestionQueue() {
const questionQueue = [];
entries.forEach(entry => {
questionQueue.push(<Question
entry={entry}
goToNextQuestion={this.goToNextQuestion}
/>)
});
this.setState({ questionQueue });
}
goToNextQuestion() {
console.log('Go to next question request is received.');
this.setState({ currentQuestionIndex: this.state.currentQuestionIndex + 1 }, () => {
console.log('Current question index is now: ', this.state.currentQuestionIndex);
})
}
render() {
if(this.state.questionQueue !== 0) {
return <React.Fragment>
<IntermediateRenderer
allQuestionComponents={this.state.questionQueue}
questionIndexToRenderNext={this.state.currentQuestionIndex}
/>
</React.Fragment>
} else {
<View>
<Text>
Questions are loading.
</Text>
</View>
}
}
}
解决方案
好吧,我想你只是忘记了 return 声明:
render() {
if(this.state.questionQueue !== 0) {
return <React.Fragment>
<IntermediateRenderer
allQuestionComponents={this.state.questionQueue}
questionIndexToRenderNext={this.state.currentQuestionIndex}
/>
</React.Fragment>
} else {
return <View>
<Text>
Questions are loading.
</Text>
</View>;
}
}
似乎它第一次运行良好,但是当您继续处理下一个问题时,它会因缺少 return 语句而失败并且什么也不显示。
推荐阅读
- firebase - 帐户不使用 GCP 计算时 GCP Compute Engine API 中的神秘指标
- python - 如何在没有单独的环境变量系统的情况下在本地从 Helm 获取值?
- python - 如何在 Python 中使生成的矩阵不重复?
- task - 创建虚拟 asyncio.Task
- directory - 使用 xargs 创建远程目录
- java - HackerRank-类解决方案中的方法calculateSum不能应用于给定类型
- javascript - 无法再在 Chrome 中检查对象
- python - 将枕头 Gif 复制到 Windows 剪贴板
- c++ - 如何从不同的类中获取函数来调用在 Main 中声明的对象?
- spring-boot - 如何在 Spring Boot 2 中将 MDC 与 hystrix 一起使用?