【问题标题】:Iterating Object with for-in loop in reactjs在 reactjs 中使用 for-in 循环迭代对象
【发布时间】:2021-11-24 13:56:52
【问题描述】:

这是一个 Reactjs 代码。在这里,我正在尝试迭代和打印对象数据。但是,面临一个错误——> TypeError: Cannot read properties of undefined (reading 'state')。我想知道我在这里做错了什么。

import React, { Component } from 'react'

class App extends Component {

  state = {
    posts: {
      ASlot: true,
      BSlot: true,
      CLive: true,
      DRedirect: true
    }
  }

  Club() {
  for(const property in this.state.posts) {
    console.log('hello')
    // console.log(`${property}: ${this.state.posts[property]}`);
  }
}

  render() {
    return <div>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <span> hey, i am left text </span>
        <button onClick={this.Club}> Click Club </button>
      </div>
    </div>;
  }
}

export default App;

【问题讨论】:

  • 您需要将this 绑定到事件处理程序或仅使用箭头函数来解决问题。在此处阅读有关 this 绑定的更多信息 - freecodecamp.org/news/…
  • 是的,我怎么会忘记这个。谢谢 Dhilip。
  • 参考这个stackoverflow.com/questions/45998744/…,你需要将你所有的事件处理函数绑定到this。所以在你的情况下,onClick={this.Club.bind(this)} 解决了这个问题。

标签: javascript reactjs for-in-loop


【解决方案1】:
import React from "react";
import "./styles.css";

class App extends React.Component {
  state = {
    posts: {
      name: "naveen",
      mail: "naveen9@gmail.com"
    }
  };
  club() {
    if (this.state.posts) {
      for (const property in this.state.posts) {
        console.log(property);
      }
    }
  }
  render() {
    return (
      <div>
        <button onClick={() => this.club()}>click</button>
      </div>
    );
  }
}
export default App;

您可以使用条件类。它对我有用,您可以在此处查看 https://codesandbox.io/embed/cool-cerf-fxh9u?fontsize=14&hidenavigation=1&theme=dark

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 2015-08-10
    • 1970-01-01
    • 2017-02-08
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多