简体   繁体   中英

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

I am in progress of doing weather app , and i am calling API to send me back weather data so i am reciving back an JSON , it looks somehow like that:

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

so , i have a table where in every row i have to do same map method on the list from api and it looks as beneath:

<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>

and there is few more rows a lot of repetition as you can see , so i thought of making this code shorter and simpler , than come up with idea of using this kind of function for that:

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>
                )
        }  
        });
    }
}

and here i found issue , how to call the function or change it so after i gave a parameter it will go through the tree to prop i need , thought of using spread operator from ES6 , but dont have a clue how should i implement it.

Provide a function that will get the desired property from the object:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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