【问题标题】:Looping through nested list in array react循环遍历数组反应中的嵌套列表
【发布时间】:2020-03-21 23:42:17
【问题描述】:

我有一个对象数组,其中一个对象是一个不同长度的列表(因对象而异)。我试过做一个嵌套的地图函数,但这不起作用,对于嵌套函数(参见下面的示例),我收到错误“user.people.map 不是函数”。

我在下面包含了一些示例代码和数据来解释。

数据文件

export default [
{
  id: uuid(),
  name: 'Random',
  people: ['x','y','z']
},
{
  id: uuid(),
  name: 'Modnar',
  people: ['a','b']
}
]

代码

  import data from './data'
  const users = useState(data);

  {users.map(u => {
      {u.people.map(x => {
        return "hey"
      })}
  })}

【问题讨论】:

  • 向我们展示您在代码文件中导入数据的代码
  • user.people.map 抛出错误而不是 users.map 的事实表明导入是正确的,但您正在为非数组的 people 属性分配一个值。您是否在代码中的任何位置更改数据数组?
  • @MarioNikolaus 这只是一个导入声明。除了那里的东西,我没有做任何改变!

标签: javascript reactjs


【解决方案1】:

您的问题在于您的第一行代码const users = useState(data)。如果您将其替换为以下const [users, setUsers] = useState(data),它将起作用。

它正在从useState 返回的数组中解构用户对象。第二个值是状态的设置器。

你可以找到一个演示here

【讨论】:

    【解决方案2】:

    这是工作代码 - https://codesandbox.io/s/blissful-bouman-t8ksy

    Hope this helps!
    
    import React from "react";
    import "./styles.css";
    
    export default class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          users: [
            {
              id: "uuid",
              name: "Random",
              people: ["x", "y", "z"]
            },
            {
              id: "uuid",
              name: "Modnar",
              people: ["a", "b"]
            }
          ]
        };
      }
      render() {
        return (
          <div>
            {this.state.users.map(u => {
              let str = u.people.map(x => {
                return "This is people";
              });
              return (
                <h1>
                  {u.name} {str}
                </h1>
              );
            })}
          </div>
        );
      }
    }
    

    【讨论】:

    • 谢谢!我正在使用 const Function name = Props => {} 箭头函数,这不起作用,我应该更改我的组件吗?到目前为止,它是一个无状态函数。
    • 最受欢迎...您可以使用相同的 const 函数并单独嵌入返回逻辑。这应该做✌️
    • 再次感谢,但是当我嵌入逻辑时,我总是遇到同样的错误。你能指点我把它转换成箭头函数吗?
    • PS 我已经根据您的建议更新了我的代码。
    【解决方案3】:

    将两个阵列合二为一,做管道?

    const data = []
    const descStr = `<h1>Should print as many times as there are entries in 
    the list</h1>`
    users.forEach(user => {
      data.push({...user, desc: descStr.repeat(users.length)})
    })
    
    {data.map((user) =>
    return(<div>
      <h1>{user.name}</h1>
     {user.desc}
    
    </div>)
    

    【讨论】:

    • 这个没用,不需要退货。
    • 编辑了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    相关资源
    最近更新 更多