簡體   English   中英

無法從 React state 訪問對象數組中的值

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

在 this.state 中存儲對象數組后,我嘗試像Array[random].someValue一樣訪問 object 中的值,但它顯示錯誤Array[random] is undefined 但它適用於Array[random]返回 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() {

請幫忙...

您的構造函數在componentDidMount之前調用,因此沒有可用的state.data (因為您將其設置為undefined )。

您必須將newQuestion調用移動到渲染 function 或componentDidUpdate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM