【问题标题】:React - Display all properties of an object [duplicate]React - 显示对象的所有属性[重复]
【发布时间】:2018-06-28 17:30:57
【问题描述】:

我敢肯定,这是一个简单的问题,但实际上我找不到我的错误在哪里。 我有一个组件,其中一个对象没有固定数量的属性。 实际上我无法显示对象的所有属性。

import React, { Component } from 'react';

class FreightRelayWithPricesAndAreas extends Component {

    constructor(props) {
        super(props);
        this.state = {
          freightRelayPrice: props.freightRelayPrice
        };
    }

    render() {
      const Fragment = React.Fragment;
      return (
        <Fragment>
          <tr>
            {
              Object.keys(this.state.freightRelayPrice).map(function(key) {
                  return <td className="whiteSpaceNoWrap">{ this.state.freightRelayPrice[key] }</td>
              })
            }
          </tr>
        </Fragment>
      )
    }
}

export default FreightRelayWithPricesAndAreas

错误总是:

app.js:57763 Uncaught TypeError: Cannot read property 'state' of 未定义

在 app.js:57763

在 Array.map() 处

在 FreightRelayWithPricesAndAreas.render (app.js:57759)

在finishClassComponent (app.js:48488)

在 updateClassComponent (app.js:48465)

在 beginWork (app.js:48840)

在 performUnitOfWork (app.js:50839)

在工作循环 (app.js:50903)

在 HTMLUnknownElement.callCallback (app.js:41157)

在 Object.invokeGuardedCallbackDev (app.js:41196)

正如我已经说过的,我确信这很简单,但实际上我看不出发生这种情况的原因。提前感谢您的帮助!

【问题讨论】:

  • this.state = { shippingRelayPrice: this.props.freightRelayPrice };
  • StackOverflow 上这个问题有几十个重复

标签: reactjs components


【解决方案1】:
Object.keys(this.state.freightRelayPrice).map(function(key) {
   return <td className="whiteSpaceNoWrap">{ this.state.freightRelayPrice[key] }</td>
})

内部回调函数this 本身就是一个函数上下文。你可以使用箭头功能

Object.keys(this.state.freightRelayPrice).map((key) => {
   return <td className="whiteSpaceNoWrap">{ this.state.freightRelayPrice[key] }</td>
})

【讨论】:

  • 感谢您的帮助和解释。就是这样!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 2011-09-20
  • 2013-10-31
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多