javascript - React 试图循环遍历状态对象

标签 javascript reactjs

我目前正在尝试创建一个组件,将按钮的点击附加到 DOM 元素的父组件。但是我在使初始循环工作时遇到问题。这是我正在做的,

 class GenerateInvoice extends Component {

  constructor(props) {
    super(props);
    this.state = {
      'invoice': {
        'items' : {}
      }
    };

    this.onAddChild = this.onAddChild.bind(this);
  }

  render() {
    const children = [];
    for (var i = 0; i < Object.keys(this.state.invoice.items); i += 1) {
      children.push(<InvoiceItemForm key={i} number={i} />);
    };
    return(
      <div>
        <a href="" onClick={this.onAddChild}>Add New Item</a>
        {children}
      </div>
    )
  }

  onAddChild = (e) => {

    e.preventDefault();
    let invoice = this.state.invoice.items;
    this.setState({ invoice : {'id' : 'INV001'} });
  }


}

export default GenerateInvoice ;

然而,当我使用 onAddChild 回调客户端时,我得到了

Cannot convert undefined or null to object

为什么会这样?

这是我的测试项目的链接,

https://codesandbox.io/s/0qx9w1qrwv

最佳答案

你在这里覆盖了你的状态:

let invoice = this.state.invoice.items;
this.setState({ invoice : {'id' : 'INV001'} });

在那之后你的状态将是

{ invoice: {'id': 'INV001'} }

并且 items 属性将消失。

如果你想添加一个项目,像这样的东西会起作用:

let invoice = this.state.invoice;
// creates an updated version of the items without changing the original value
let updatedItems = invoice.items.concat({'id': 'INV001'});
// creates a new version of the invoice with the updated items
let updateInvoice = { ...invoice, items: updatedItems };
// update the invoice on the state to the new version
this.setState({ invoice });

关于javascript - React 试图循环遍历状态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46706630/

相关文章:

reactjs - React 组件中的 JSX 将西里尔文文本显示为 habra-codabra

javascript - 正则表达式匹配当前 URL 中的字符串(包括通配符)

javascript - 如何在我的 Angular 应用程序中实时更新购物车中的商品数量?

javascript - 如何在 React 中使用 Emscripten JavaScript 文件

javascript - 如何组合目标数组在javascript中保存相同的键

javascript - hr 在表格内但全宽

Javascript 测试 stub 全局变量函数

javascript - 调试ajax,重新发送请求

javascript - 将行添加到具有固定标题的 HTML 表格

javascript - 如何避免使用eval调用不同的函数