簡體   English   中英

用 this.state 返回一個變量

[英]returning with this.state a variable on react

this.state.onlyvar.TheName顯示為undefined ,我不知道為什么。

import  React, { Component } from 'react';

class Thevar extends Component {
  constructor(props) {
    super(props);
    this.state = {
        onlyvar: [{
            TheName:"getter Name"
            }]
    }
  }
render() {
    return (
        <div>
            TheOnlyVar: <p>{console.log(this.state.onlyvar.TheName)}</p>
        </div>
    )
}
}

export default Thevar;

在您的代碼中有兩個錯誤:

  1. onlyvar是一個數組,要訪問它的項目,您應該使用索引來指定您想要的項目,在這種情況下,第一個(也是唯一一個)項目。

  2. console.log()在控制台中打印值,而不是在頁面上。

這是更正后的代碼:

return (
    <div>
        TheOnlyVar: <p>{this.state.onlyvar[0].TheName}</p>
    </div>
)

暫無
暫無

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

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