简体   繁体   English

使用 React.js 映射对象

[英]Mapping an Object with React.js

I am trying to use the map function to map an object.我正在尝试使用 map 函数来映射对象。 I've seen similar posts where this has worked using Object.keys but I can't seem to get it to work.我看过类似的帖子,其中使用 Object.keys 进行了操作,但我似乎无法使其正常工作。 I realize that you can't map an object directly.我意识到你不能直接映射一个对象。

A portion of my json is below:我的 json 的一部分如下:

{
    "orders": [
        {
            "deadline": 1563046159,
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            "id": "83f007d6",
            "name": "Work order 83f007d6",
            "workerId": 1
        },
        {
            "deadline": 1562752687,
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            "id": "cb23c526",
            "name": "Work order cb23c526",
            "workerId": 1
        },
]
}

Relevant Code相关代码

class App extends Component {

state = {
ordersData: [],
workersData : []
}

// fetch for the first time page loads
componentDidMount() {

fetch("https://www.hatchways.io/api/assessment/work_orders")
  .then(response => response.json())
  .then(data => {
    this.setState({
      ordersData: data,
    });
    console.log(this.state.ordersData)
  })
  .catch(err => {
    console.log(err)
  });  
}

render() {
let allOrders = this.state.ordersData.orders;

return (
  <div> 
  {Object.keys(allOrders).map((keyName, i) => (
    <li className="allOrders" key={i}>
        <span className="input-label">key: {i} Name: {allOrders[keyName]} 
 </span>
    </li>
  ))}
  </div>
  )}}

I get this error : TypeError: Cannot convert undefined or null to object我收到此错误:TypeError:无法将未定义或空值转换为对象

  1. You are not waiting for your async to resolve before trying to access your async data (this is the first issue, which is causing the error you are seeing.) The component tries to render with default data while componentDidMount is fired.在尝试访问异步数据之前,您不是在等待异步解决(这是第一个问题,它会导致您看到的错误。)组件尝试在 componentDidMount 被触发时使用默认数据呈现。

  2. ordersData is an array in your default state, not an object, so you are accessing it wrong ordersData 是默认状态下的数组,而不是对象,因此您访问它是错误的

  3. allOrders is an array, not an object, so you could just map it directly. allOrders 是一个数组,而不是一个对象,因此您可以直接映射它。 Then you can use the .keys() method on the results of that map.然后您可以在该地图的结果上使用 .keys() 方法。

To resolve 1 and 2 you should give a more complete default state so that you don't get the TypeError要解决 1 和 2,您应该提供更完整的默认状态,以免出现 TypeError

state = {
    ordersData: {orders:[]},
    workersData : []
}

To resolve 3 you will need to change to something along the lines of:要解决 3,您需要更改为以下内容:

allOrders.map(order => {
 //now you have each order, you can use Object.keys(order).map() to get each property of the order
}

I hope this makes sense and clears things up.我希望这是有道理的,并使事情变得清晰。 Comment if you have questions about the individual parts.如果您对各个部分有疑问,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM