Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

reactjs - Can't access property in render method of React

I'm trying to access a property of the array I get from the json file, but because I'm using Component DidMount it seems like I can't, and it says it is undefined. I'm trying to access perguntas[0] inside of the render method.

import React, {Component} from 'react';
import './App.css';
import Pergunta from './Pergunta';


class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
        perguntas: undefined,
        isLoaded: false
    }
  }


  componentDidMount = () => {
    fetch('http://127.0.0.1:8000/api/perguntas')
        .then(res => res.json())
        .then(json => this.setState({
                perguntas: json.data,
                isLoaded: true
        }))
  }

  componentDidUpdate() {
      console.log(this.state.perguntas)
  }

  /*
    sortear = (perguntas) => {
        let randomIndex = Math.floor(Math.random() * 10);

        return perguntas[randomIndex]
    }*/

    render() {
            const {perguntas} = this.state
            //let pergunta = this.sortear(perguntas)

            return (
                // testes...

                <div>
                    <div>{JSON.stringify(perguntas[0])}</div>
                </div>


                //<Pergunta pergunta={ perguntaRandom['id'] }/>
            )
        }

}

export default App;
question from:https://stackoverflow.com/questions/65909864/cant-access-property-in-render-method-of-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the solution, it's the first if statement inside render() method.

render() {
        const {perguntas, isLoaded} = this.state
        if (!isLoaded) {
            return <div>Loading...</div>
        }
        else {
            let randomIndex = Math.floor(Math.random() * 10)
            let pergunta = perguntas[randomIndex]
            let texto = pergunta.texto
            let opcao1 = pergunta.opcao1
            let opcao2 = pergunta.opcao2
            let opcao3 = pergunta.opcao3
            let opcao4 = pergunta.opcao4
            //let imagem = pergunta.urlImagem

            return (
                <Pergunta texto={texto} opcao1={opcao1} opcao2={opcao2} opcao3={opcao3} opcao4={opcao4}/>
            )
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...