【问题标题】:I'm unable to retrieve state.Check this code and my output我无法检索状态。检查此代码和我的输出
【发布时间】:2019-04-02 02:42:43
【问题描述】:

我已经在 Header 类中声明了一个状态。但我无法使用 {this.state.characters} 检索该状态。请帮我解决。

class Header extends React.Component{
    state={
        characters: [
            {
                'name': 'sakthi'
            }
        ]
    };
    render(){
        var style1={
            color:'#9876[enter image description here][1]56'
        }
    return(
        <div>
            <h1>Hello World !!</h1>
            <h4 style={style1}>{this.state.characters}</h4>
        </div>
    );
}
}

“sakthi”应该打印在我的屏幕上。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    this.state.characters 是一个对象数组,React 不可能知道如何打印或打印哪个属性。因此,您应该使用 map 函数循环遍历数组并定义您想要的方式

    return(
      <div>
        <h1>Hello World !!</h1>
        {
          this.state.characters
            .map(x => (<h4 style={style1}>{x.name}</h4>))
        }
      </div>
    );
    

    【讨论】:

    • @sakthikumaran:没问题,只要记住将其标记为参考答案,以防其他人遇到类似问题。谢谢
    【解决方案2】:

    您应该像 JSX 数组一样表示对象数组 (this.state.characters) 来呈现它:

    class Header extends React.Component {
      state = {
        characters: [
          {
            'name': 'sakthi'
          }
        ]
      };
    
      renderCharacters = () => this.state.characters.map((c, i) => (
        <h4 key={i}>{c.name}</h4>
      ));
    
      render(){
        return(
          <div>
            <h1>Hello World!!</h1>
            {this.renderCharacters()}
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多