首页 > 解决方案 > 反应:无法替换渲染()方法中的组件

问题描述

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

标签: reactjsreact-native

解决方案


好吧,我想你只是忘记了 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 语句而失败并且什么也不显示。


推荐阅读