【问题标题】:React native react sub array in object反应对象中的本机反应子数组
【发布时间】:2018-10-06 07:52:37
【问题描述】:

我厌倦了从 render() 中的对象打印出子数组数据..

数据对象 JSON:

{
"genres": [
    {
        "id": 27,
        "name": "aa"
    },
    {
        "id": 878,
        "name": "bb"
    },
    {
        "id": 28,
        "name": "cc"
    },
    {
        "id": 53,
        "name": "dd"
    }
], 
"status": "Released",
"tagline": ""
}

MyMainScreen.js

render() {
    return (
        <Container>
            <Content style={{marginLeft:0,marginRight:0}}>
                <InfoSection key={this.state.data.id} info={this.state.data}/>
            </Content>
        </Container>
    );}

InfoSection .js

const InfoSectionCard = ({ info }) => (
<View>
    <Text style={styles.cardGenreItem}>{info.genres}</Text>
</View>
);
export default InfoSectionCard;

我使用.map 来解决这个问题.. 它通常不会起作用。 使用JSON.stringify(obj) 时可以打印出所有JSON对象

当我尝试时

&lt;Text style={styles.cardGenreItem}&gt;{info.genres}&lt;/Text&gt;

react 错误消息是 Invariant Violation: Objects are not valid as a React child (found: object with keys {id, name})。如果您打算渲染一组子项,请改用数组。

然后添加'.map'

info.genres.map(item =&gt;&lt;Text style={styles.cardGenreItem}&gt;{item.name}&lt;/Text&gt;)

反应错误消息是 TypeError: undefined is not an object(evalating 'info.genres.map')

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您的问题不是很清楚,但我认为 json 中显示的数据被解析并存储在您的组件状态中是否正确?如果您希望 InfoSection.js(应该是 .jsx)为每个元素显示一个 Text 组件,那么您需要这样做:

    const InfoSectionCard = ({ info }) => (
        <View>
            {info.genres.map(genre => <Text style={styles.cardGenreItem} key={genre.id}>{genre.name}</Text>}
        </View>
    );
    

    导出默认的InfoSectionCard;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2023-03-07
      相关资源
      最近更新 更多