反应:无法替换render()方法中的组件

时间:2019-01-09 08:15:51

标签: reactjs react-native

我正在为练习创建一个简单的问答游戏,但是在问题更改方面存在一些问题。我打算一一处理渲染问题的方式是在数组内部以组件状态(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>
    }
  }
} 

1 个答案:

答案 0 :(得分:0)

好吧,我想您只是忘记了退货声明:

  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语句而失败,并且什么也不显示。