简体   繁体   English

如何在React Native中获取对象数组中的对象

[英]How to get objects in array of object in React Native

I'm kind of lost to access some info in my static data. 我有点迷失于访问静态数据中的某些信息。 Here's the data : 这是数据:

{
 "info1": {
    "label": "label",
    "class": "class-css",
    "title": "title",
    "text": "text",
    "number": "20",
    "tags": [
         {
            "name": "#twitter"
        },
        {
            "name": "#myspace"
        }
    ]
 },
 "info2": {
    "label": "label",
    "class": "class-css",
    "title": "title",
    "text": "text",
    "number": "20",
    "tags": [
         {
            "name": "#instagram"
        },
        {
            "name": "#facebook"
        }
    ]
  }
}

Then I get the first info like that : 然后我得到第一个这样的信息:

this.setState({
    currentLabel: this.state.labels["info1"]
})

This is why I want and then I want to display info in a component and it's working until I try to get tags information. 这就是为什么我想要然后在组件中显示信息的原因,并且在我尝试获取tags信息之前它一直有效。 I tried a .map() but without success and error. 我尝试了.map()但没有成功和错误。

<View>
   <Text>{infoDetail.title}</Text>
   <Text>{infoDetail.text}</Text>
   <Text>How do I get "tags" information</Text>
</View>

Is it possible to access these objects in the array "tags" ? 是否可以访问数组“标签”中的这些对象?

yes you can call tags as follows infoDetail.tags and do map on it 是的,您可以按照infoDetail.tags如下调用标签并在其上进行映射

render(){
      const tagItems = infoDetail && infoDetail.tags.map((item, index) => {
          return <Text key={index}>{item.name}</Text>
      });
      return(
        <View>
          <Text>{infoDetail.title}</Text>
          <Text>{infoDetail.text}</Text>
          {tagItems}
        </View>
      )
}

Probably something like this. 大概是这样的。 <Text>{infoDetail.tags.map(tag => {/*render */})}</Text>

You can try Object.keys() and Array.prototype.reduce() to get your favorite data: 您可以尝试Object.keys()Array.prototype.reduce()来获取您喜欢的数据:

 const data = { "info1": { "label": "label", "class": "class-css", "title": "title", "text": "text", "number": "20", "tags": [ { "name": "#twitter" }, { "name": "#myspace" } ] }, "info2": { "label": "label", "class": "class-css", "title": "title", "text": "text", "number": "20", "tags": [ { "name": "#instagram" }, { "name": "#facebook" } ] } }; const tags = Object.keys(data).reduce((result, key) => { return result.concat(data[key].tags); }, []) console.log(tags); /* tags = [ { "name": "#twitter" }, { "name": "#myspace" }, { "name": "#instagram" }, { "name": "#facebook" } ] */ 

Here is a full working code. 这是完整的工作代码。 Since your labels state property is an object, you need to map it somehow. 由于labels state属性是一个对象,因此您需要以某种方式对其进行映射。 I've chosen Object.values here. 我在这里选择了Object.values You can use Object.keys or even Object.entries according to your needs. 您可以根据需要使用Object.keys甚至Object.entries

I've used a separate Info component and passed the values to it, then render there. 我使用了一个单独的Info组件,并将值传递给它,然后在那里渲染。 In this component, we are again mapping the tags , then rendering the list. 在此组件中,我们再次映射tags ,然后呈现列表。

 class App extends React.Component { state = { labels: { info1: { label: "label1", class: "class-css", title: "title", text: "text", number: "20", tags: [ { name: "#twitter", }, { name: "#myspace", }, ], }, info2: { label: "label2", class: "class-css", title: "title", text: "text", number: "20", tags: [ { name: "#instagram", }, { name: "#facebook", }, ], }, }, } render() { const { labels } = this.state; return ( <div> { Object.values( labels ).map( value => <Info label={value} key={value.label} /> ) } </div> ); } } const Info = ( props ) => { const { title, text, tags } = props.label; const tagList = tags.map( tag => <p key={tag.name}>{tag.name}</p> ); return ( <div style={{ border: "1px solid gray", marginTop: "-1px" }}> <p>{title}</p> <p>{text}</p> <div>{tagList}</div> </div> ); }; ReactDOM.render( <App />, document.getElementById("root") ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

Update 更新资料

If your data is totally static then @Xavi A.'s method is a good option. 如果您的数据是完全静态的,那么@Xavi A.的方法是一个不错的选择。 I don't know how is your list but I provide a simple code including something like you want here. 我不知道您的列表如何,但是我提供了一个简单的代码,其中包括您想要的内容。

 const labels = { info1: { label: "label1", class: "class-css", title: "title", text: "text", number: "20", tags: [ { name: "#twitter" }, { name: "#myspace" } ] }, info2: { label: "label2", class: "class-css", title: "title", text: "text", number: "20", tags: [ { name: "#instagram" }, { name: "#facebook" } ] } }; class App extends React.Component { state = { currentLabel: Object.keys(labels)[0] }; handleInfoChange = info => this.setState({ currentLabel: info }); renderList = () => ( <ul> {Object.keys(labels).map(info => ( <Item key={info} info={info} onClick={this.handleInfoChange} /> ))} </ul> ); render() { const { currentLabel } = this.state; return ( <div> {this.renderList()} <Info currentLabel={currentLabel} /> </div> ); } } const Item = props => { const { info, onClick } = props; const handleClick = () => onClick(info); return <li onClick={handleClick}>{info}</li>; }; const Info = props => { const { currentLabel } = props; const { title, text, tags } = labels[currentLabel]; const tagList = tags.map(tag => <p key={tag.name}>{tag.name}</p>); return ( <div style={{ border: "1px solid gray", marginTop: "-1px" }}> <p>{title}</p> <p>{text}</p> <div>{tagList}</div> </div> ); }; ReactDOM.render( <App />, document.getElementById( "root" ) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

No need to save all the static data in your state, you can keep your state cleaner by just saving the selected label: 无需将所有静态数据保存在状态中,只需保存选定的标签即可使状态更整洁:

onLabelSelect = label => {
    //label will be "info1" for example
    this.setState({
        currentLabel: label 
    })
}

Then in your render: 然后在渲染中:

render(){ 
    //get infoDetail from staticData 
    const infoDetail = staticData[this.state.currentLabel]         
    return (
        <View>
            <Text>{infoDetail.title}</Text>
            <Text>{infoDetail.text}</Text>
            {infoDetail.tags.map( ({name}) => <Text>name</Text>)}
        </View>
    )
}

Note about the map. 请注意地图。 This: 这个:

{infoDetail.tags.map( ({name}) => <Text>name</Text>)}

is a shorter version of: 是以下内容的简称:

{infoDetail.tags.map( item => {
    return <Text>item.name</Text>
})}

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

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