在“ setState”上需要帮助

时间:2019-10-04 19:52:50

标签: reactjs

我是新来写React的人。我有一个问题-初始化变量时,“ setState”中的变量为null。我的任务-在页面中显示问题及其答案。我通过提取检查了回调,我得到了全部。我的代码:

    constructor(props) {
            super(props)
            this.state = {
                question: "",
                isFetching: true,
                answers: []
            };

            this.componentDidMount = this.componentDidMount.bind(this);
        }

        componentDidMount() {
            var VariableQuestion;
            var AnswersForQuestion = [];
            fetch('https://localhost:44392/api/QuizData/GetQuestions?numberOfQuestion=1')
                .then(response => response.json())
                .then(function (result) {

                        VariableQuestion = result.text;
                        var answers = result.allAnswers;
                        for (var z = 0; z < answers.length; z++)
                        {      
                            var ans = answers[z].text;
                            AnswersForQuestion.push(ans);                                                       
                    }
                    console.log(VariableQuestion);

                });

            this.setState({
                question: VariableQuestion,
                isFetching: false,
                answers: AnswersForQuestion
            });

        }


        render() {
            const { question, isFetching, answers } = this.state;

            if (isFetching) return <div>...Loading</div>;

            return (
                <div>
                    <h1>{question}</h1>
                    <h1>{answers}</h1>
                </div>

            )
        } 
}

4 个答案:

答案 0 :(得分:0)

提取是一个异步任务。 request函数被抛出到后台堆栈,因此您的setState值为空值,因为尚未完成任何响应。
只需将setState移到请求的.then()内部,以便它等待响应。 您可能想看看here

答案 1 :(得分:0)

在这里处理异步代码时,fetch返回一个promise,因此一旦状态被解决,就可以设置状态
将setState移入内部,然后作为

fetch('https://localhost:44392/api/QuizData/GetQuestions?numberOfQuestion=1')
    .then(response => response.json())
    .then((result) => {

            VariableQuestion = result.text;
            var answers = result.allAnswers;
            for (var z = 0; z < answers.length; z++)
            {      
                var ans = answers[z].text;
                AnswersForQuestion.push(ans);                                                       
        }
        console.log(VariableQuestion);
        this.setState({
         question: VariableQuestion,
         isFetching: false,
         answers: AnswersForQuestion
        });

    });

您的操作方式是,setState将在代码之前运行

希望有帮助

答案 2 :(得分:0)

这是人为的(而不是React的),但从本质上讲,它有助于解释断开连接的位置。

  1. 设置data变量
  2. 启动异步
  3. 日志变量
  4. 完成异步并设置data变量

const asyncData = async () => await setTimeout(() => 'data', 300);

let data = 'nothing';

asyncData().then((res) => { data = res });

console.log(data);

因此,请继续输入您的代码:

componentDidMount() {

    fetch('https://localhost:44392/api/QuizData/GetQuestions?numberOfQuestion=1')
      .then(response => response.json())
      .then(function (result) {
        // no reason to have these at the top level 
        // since they only get used here.
        var VariableQuestion = result.text;
        var AnswersForQuestion = [];

        var answers = result.allAnswers;
        for (var z = 0; z < answers.length; z++) {      
          var ans = answers[z].text;
          AnswersForQuestion.push(ans);                                                       
        }
        console.log(VariableQuestion);
        // move this into your async handler.
        this.setState({
          question: VariableQuestion,
          isFetching: false,
          answers: AnswersForQuestion
        });
      });

}

答案 3 :(得分:0)

componentDidMount() {
var VariableQuestion;
var AnswersForQuestion = [];
fetch('https://localhost:44392/api/QuizData/GetQuestions?numberOfQuestion=1')
  .then(response => response.json())
  .then(function (result) {

    VariableQuestion = result.text;
    var answers = result.allAnswers;
    // for (var z = 0; z < answers.length; z++)
    {
      var ans = answers[z].text;
      AnswersForQuestion.push(ans);
    }
    console.log(VariableQuestion);
    this.setState({
      question: VariableQuestion,
      isFetching: false,
      answers: AnswersForQuestion
    });
  }.bind(this));
}