简体   繁体   English

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

[英]Unable to access values in an Array of Objects, from the React state

After Storing the array of objects in the this.state, I tried to access the value in the object like Array[random].someValue but it shows error Array[random] is undefined .在 this.state 中存储对象数组后,我尝试像Array[random].someValue一样访问 object 中的值,但它显示错误Array[random] is undefined But it works for Array[random] returns an object.但它适用于Array[random]返回 object。 Why can't i access the value inside that object...?为什么我不能访问 object... 中的值?

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() {

Please help...请帮忙...

Your constructor is called before componentDidMount so there is no state.data available (since you set it to undefined ).您的构造函数在componentDidMount之前调用,因此没有可用的state.data (因为您将其设置为undefined )。

You either have to move the newQuestion call to the render function or to componentDidUpdate您必须将newQuestion调用移动到渲染 function 或componentDidUpdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM