在JSON数组中渲染

时间:2020-02-13 06:12:25

标签: reactjs react-native react-native-android

我有一个订单页面,在这里我可以显示一个人下的订单,我在全局JSON中拥有的数据能够访问this.state.data,但是,我也想访问内部的数组产品该JSON并显示其项目,知道如何相应地对其进行循环吗?请帮忙。

我的日志是:

[{
  "__v": 1,
  "_id": "5e44e68d7ce9f60c5cfd0c6b",
  "addressLineOne": "G",
  "city": "J",
  "customerName": "Tr",
  "mobile": 8697779335,
  "order_id": "order_EG7aMZwcx9uQf3",
  "order_verification_status": false,
  "payment_method": "COD",
  "payment_status": false,
  "phoneNumber": 8697779335,
  "pincode": 713211,
  "products": [
    [Object]
  ],
  "state": "B",
  "street": "V"
}, {
  "__v": 1,
  "_id": "5e44e6b87ce9f60c5cfd0c79",
  "addressLineOne": "Fd",
  "city": "J",
  "customerName": "Tr",
  "landmark": "M",
  "mobile": 8697779335,
  "order_id": "order_EG7b82pB6uKRXo",
  "order_verification_status": false,
  "payment_method": "COD",
  "payment_status": false,
  "phoneNumber": 8697779335,
  "pincode": 713211,
  "products": [
    [Object]
  ],
  "state": "V",
  "street": "D"
}]

我的整个代码如下:

import * as React from 'react';
import {
  Text,
  View,
  StatusBar,
  StyleSheet,
  FlatList,
  ActivityIndicator,
  Platform,
  Image,
} from 'react-native';
import { SearchBar, Card, Button } from 'react-native-elements';
import { Appbar } from 'react-native-paper';

export default class Order extends React.Component {
  constructor(props) {
    super(props);
    //setting default state
    this.state = { 
      isLoading: true, 
      search: '' , 
      data: [], 
      orderplaced: [],

    };

  }
  componentDidMount() {
    return fetch('some url')
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            isLoading: false,
            data: responseJson.orderplaced
          },
          console.log('a',responseJson.orderplaced[0].products),

        );
      })
      .catch(error => {
        console.error(error);
      });
  }

  render() {
    if (this.state.isLoading) {
      //Loading View while data is loading
      return (
        <View style={{ flex: 1, paddingTop: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }
    return (

      <View style={{ backgroundColor: '#f0f8ff', height: '100%' }}>
        <Appbar.Header style={{ backgroundColor: 'white' }}>
        <Appbar.BackAction onPress={() =>this.props.navigation.navigate('User')} />
          <Appbar.Content title="Orders" />
        </Appbar.Header>
        <View>
          <SearchBar
            round
            lightTheme
            searchIcon={{ size: 24 }}
            onChangeText={text => this.SearchFilterFunction(text)}
            onClear={text => this.SearchFilterFunction('')}
            placeholder="Type Here..."
            placeholderTextColor="black"
            value={this.state.search}
            containerStyle={{
              backgroundColor: '#f0f8ff',
              borderBottomColor: '#f0f8ff',
              borderTopColor: '#f0f8ff',
              padding: 10,
            }}
          />

 <FlatList
          showsVerticalScrollIndicator={false}
          index = {0}
          data={this.state.data}
          // ItemSeparatorComponent={this.ListViewItemSeparator}
          //Item Separator View
          renderItem={({ item }) => (
            // Single Comes here which will be repeatative for the FlatListItems


              <Card
              containerStyle={{ padding: 10, marginLeft: 3, marginRight: 3 }}>
              <View>
        <View style={{ flexDirection: 'row' }}>
          <Image
            style={{ height: 100, width: 100, marginLeft: 0 }}
            source={{
              uri:
                item.urlImg}}
          />

          <View sttle = {{ flexDirection: 'column'}}>
<Text style={{ paddingLeft: 20 }}>Order Id - {item._id}</Text>
          <Text style={{ paddingLeft: 20 }}>{item.title}</Text>
            <Text>{this.renderProducts}</Text>
          <Text style={{ paddingLeft: 20 }}>INR{item.totalPrice} . {item.customerName} </Text>
          <Text style={{ paddingLeft: 20 }}>Time </Text>
          </View>
        </View>
      </View>
            </Card>



          )}
          enableEmptySections={true}
          style={{ marginTop: 10 }}
          keyExtractor={(item) => item.order_id}
        />
        </View>

      </View>
    );
  }
}

因此,基本上,我必须显示来自订购的JSON文件的产品数据,并显示来自全局JSON的customerName,orderid等。 我必须访问内部的“产品”数组。 请帮助,并告诉我是否还有其他要求。

我的响应JSON日志:

hello {"orderplaced": [{"__v": 1, "_id": "5e44e68d7ce9f60c5cfd0c6b", "addressLineOne": "G", "city": "J", "customerName": "Tr", "mobile": 8697779335, "order_id": "order_EG7aMZwcx9uQf3", "order_verification_status": false, "payment_method": "COD", "payment_status": false, "phoneNumber": 8697779335, "pincode": 713211, "products": [Array], "state": "B", "street": "V"}, {"__v": 1, "_id": "5e44e6b87ce9f60c5cfd0c79", "addressLineOne": "Fd", "city": "J", "customerName": "Tr", "landmark": "M", "mobile": 8697779335, "order_id": "order_EG7b82pB6uKRXo", "order_verification_status": false, "payment_method": "COD", "payment_status": false, "phoneNumber": 8697779335, "pincode": 713211, "products": [Array], "state": "V", "street": "D"}]}

3 个答案:

答案 0 :(得分:0)

因此,您可以做的只是通过以下方式遍历产品:

renderProducts = () => {

return this.state.data.products.map((data,index) => {
return(

<View>
<Text>{data.customerName}</Text>
</View>
)

});

}

在主渲染中,您可以:

render(){

return(

<View>
{this.renderProducts()}
</View>
)
}

更新:

您的新代码应如下所示:

class ABC extends Component {

renderProducts = () => {

    return this.state.data.products.map((data,index) => {
    return(

    <View>
    <Text>{data.customerName}</Text>
    </View>
    )

    });

    }


 render(){

    return(

    <View>
    {this.renderProducts()}
    </View>
    )
    }




}

现在有帮助吗?

希望有帮助。毫无疑问

答案 1 :(得分:0)

您可以使用Javascript's map function

以下示例:

{ this.state.data.map(message => (
        <div className="newmessage">
            <p>User: {message.user}</p>
            <p>Message: {message.message}</p>
        </div>
    ))}

答案 2 :(得分:0)

我建议您仔细阅读此link并检查出平板列表组件。它完全符合您的要求和其他有用的功能。