簡體   English   中英

react.js,JS:通過函數參數訪問嵌套對象的屬性

[英]react.js , JS: Getting access to nested object property through function parameter

我正在進行天氣應用程序的開發,正在調用API向我發送天氣數據,因此我正在接收JSON,它看起來像這樣:

{
 someprops: someval,
 .... ,
 list: [
   0: {
     main:{someprops},
     wind:{someprops},
     ...
   },
   1: {propsAsAbove},
    ...
   ]
 }

因此,我有一個表,在每一行中,我必須對api列表中的表執行相同的map方法,如下所示:

<tr>
    <td>hour </td>
    {weatherInfo.list.map((item,idx) => {
        while(idx < displayItemTo && idx >= displayItemFrom){
            return(
                <td>{weatherInfo.list[idx].dt_txt.slice(11,19)}</td>
            )
        }
    })}
</tr>
<tr>
    <td>temp</td>
    {weatherInfo.list.map((item,idx) => {
        while(idx < displayItemTo && idx >= displayItemFrom){
            return(
                <td>{Math.round(weatherInfo.list[idx].main.temp - 273.85)} &#8451; </td>
            )
        }
    })}
</tr>
<tr>
    <td>humidity</td>
    {weatherInfo.list.map((item,idx) => {
        while(idx < displayItemTo && idx >= displayItemFrom){
            return(
                <td>{weatherInfo.list[idx].main.humidity} % </td>
            )
        }
    })}
</tr>

而且,您可以看到幾乎沒有更多的重復行,所以我想到了使這段代碼更短,更簡單,而不是想到為此使用這種功能:

mapList(param){
    return () => {
        const weatherInfo = this.props.forecastData,
        {displayItemTo,displayItemFrom} = this.state;

        console.log('hello' + a);

        weatherInfo.list.map((item,idx) =>{
            while(idx < displayItemTo && idx >= displayItemFrom){
                return(
                    <td key={idx}>weatherInfo.param</td>
                )
        }  
        });
    }
}

在這里我發現了問題,如何調用函數或對其進行更改,因此在給定參數后它將通過樹來滿足我的需要,考慮使用ES6中的散布運算符,但不知道如何實現它。

提供一個將從對象獲取所需屬性的函數:

displayInfo(getter) {
  const weatherInfo = this.props.forecastData;
  const { displayItemTo, displayItemFrom } = this.state;

  return weatherInfo.list
    .filter((item, idx) => idx < displayItemTo && idx >= displayItemFrom)
    .map((item, idx) => (
      <td key={idx}>{getter(weatherInfo)}</td>
    ));
}

// use case
<tr>
  <td>humidity</td>
  { displayInfo(info => info.main.humidity) }
</tr>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM