从React状态无法访问对象数组中的值

时间:2020-07-30 13:21:30

标签: javascript node.js json reactjs

在this.state中存储对象数组之后,我尝试访问Array[random].someValue之类的对象中的值,但它显示错误Array[random] is undefined。但它适用于Array[random]返回一个对象。为什么我不能访问该对象内的值...?

class Quiz extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: undefined,
            q_no: 0,
            rand_q: {},
            opts: []
        }
        this.newQuestion = this.newQuestion.bind(this);
    }

    componentDidMount() {
        if(this.state.data === undefined) {
            fetch("http://restcountries.eu/rest/v2/all")
            .then(data => data.json())
            .then(data => this.setState({data: [data.map((val) => ({name: val.name, flag: val.flag}))]}))
            .then(() => console.log(this.state.data));
        }
    }

    newQuestion() {
        const state = this.state;
        const rand = Math.floor(Math.random() * 200);
        this.setState({rand_q: {name: state.data[rand].name, flag: state.data[rand].flag}, opts: [state[rand-1].name, state[rand+1].name, state[rand+2].name]});
    }
TypeError: state.data[rand] is undefined
newQuestion
src/Quiz.js:30

  27 | newQuestion() {
  28 |     const state = this.state;
  29 |     const rand = Math.floor(Math.random() * 200);
> 30 |     this.setState({rand_q: {name: state.data[rand].name, flag: state.data[rand].flag}, opts: [state[rand-1].name, state[rand+1].name, state[rand+2].name]});
     | ^  31 | }
  32 | 
  33 | render() {

请帮助...

1 个答案:

答案 0 :(得分:0)

您的构造函数在componentDidMount之前被调用,因此没有state.data可用(因为您将其设置为undefined)。

您必须将newQuestion调用移至render函数或移至componentDidUpdate