【问题标题】:How do I set an array of objects to state in React?如何在 React 中设置要声明的对象数组?
【发布时间】:2020-08-05 06:58:55
【问题描述】:

所以我在我的 node/express 后端执行 SQL 查询,并通过 JSON 将结果发送到我的 React 前端。我是 console.log 来查看我发送的信息,这似乎是有序的。但是,我似乎无法弄清楚如何将这个对象数组设置为我的状态。我收到此错误:

“对象作为 React 子对象无效(找到:带有键 {Title} 的对象)。如果您要呈现子对象的集合,请改用数组。”

这是我正在使用的组件:

import React, { Component } from 'react'

export class ShoppingCart extends Component {
    state = {
       cartItems: ['Title 1']
    };


      displayCart = () => {

          console.log('call it')
          console.log('hello from displaycart');
          fetch('http://localhost:5000/fillCart')
          .then((res) => res.json())

          .then((json) => {
              this.setState(state => {
                  const cartItems = state.cartItems.concat(json.Title);
                  return {
                      cartItems
                  };
              });
          })
      }

      componentDidMount() {
          this.displayCart();
      }

    render() {

        return (
            <div className="ShoppingCart">

                <h3>This is your shopping cart</h3>
                <ul>
                    {this.state.cartItems.map(item => (
                        <li key={item}>{item}</li>
                    ))}
                </ul>

            </div>
        )
    }
}

export default ShoppingCart

我的目标是将 json.Title(现在包含多个标题)设置到我所在州的 cartItems State 数组中,然后通过 render() 在列表中显示每个标题。但是,我对如何做到这一点感到困惑。

另外,这是我从 Node/express 后端发送的 json 数据的样子:

[
  RowDataPacket { Title: 'The Tragedy of The Korosko' },
  RowDataPacket { Title: 'Two in the Far North' }
]

为了澄清,此时我的问题不是显示信息,而是首先将其设置为状态。 任何建议肯定会受到赞赏!我已经坚持了好几天了。提前谢谢!!!

【问题讨论】:

  • 您能展示一下 JSON 响应的结构吗?
  • 显示 json 数据。
  • 这是我发送给 React 的 json 格式:[ RowDataPacket { Title: 'The Tragedy of The Korosko' }, RowDataPacket { Title: 'Two in the Far North' } ]
  • 请将其添加到原始问题中,而不是在评论中。真的很难读。
  • 我刚刚将json数据添加到原始问题中。

标签: javascript arrays reactjs state javascript-objects


【解决方案1】:

使用 Array Spreading 与当前状态和 JSON 作为响应。代码如下:

displayCart = () => {
  fetch('http://localhost:5000/fillCart')
  .then((res) => res.json())
  .then(json => {
    const newItemsArry = json.map(itm=> itm.Titles)
    this.setState({cartItems: [...this.state.cartItems, newItemsArry]}))
  }
}

【讨论】:

  • 所以更新这个答案。它消除了我在原始问题中提到的错误。但是,在浏览器中打开我的 React 工具后,cartItems 的状态设置为:cartItems: ["Title 1", undefined]。所以基本上 json 对象仍然没有被设置为状态。这个问题有什么解决办法吗?
  • 看起来你所说的json实际上是一个数组。这非常令人困惑。无论如何,我已经更新了我的答案,现在应该可以了。并找到JSON规范here
【解决方案2】:

您需要从 json 响应中提取所有标题。

这是响应格式的样子:

{
  Title: [{Title: ''}, {Title: ''}]
}

您的顶级json.Title 是一个包含对象的数组。
所以.Title 属性不存在于json.Title 上,而是存在于数组内的每个对象上。

我们可以使用map 来提取我们需要的东西。

您的 setState 可能如下所示:

this.setState(state => {
    // All titles in an array
    const titles = json.Title.map(row => row.Title)

    // Add to existing ones
    const cartItems = state.cartItems.concat(titles);

    return {
        cartItems
    };
});

【讨论】:

  • 现在它给了我以下错误:json.map 不是一个函数。对此有何建议?
  • 在这种情况下,json 不是您在问题中显示的内容。 console.log(".then: " + json); 输出 @LukeSharon 是什么?
  • @OskarHane 它是这样说的:.then: [object Object]
  • console.log(JSON.stringify(json)) 代替 @LukeSharon 怎么样?
  • @3limin4t0r 我将一行更改为您的建议。它导致了一个错误:Uncaught TypeError: Cannot read property 'then' of undefined
【解决方案3】:

Oskar Hane 的答案非常接近。这是他稍作修改的答案:

.then((json) => {
              this.setState(state => {
                  const titles = json.Title.map(row => row.Title)
                  const cartItems = state.cartItems.concat(titles);
                  return {
                      cartItems
                  };
              });
          })
      }

更改在 json.Title.map 中。需要通过数组进行映射;但是, json.map 不是通过数组映射,因为 json 不是数组。 json.Title 是数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2020-10-22
    • 2013-03-22
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多