简体   繁体   中英

How to pass object array as props to a custom component in react native?

I have fetched some data from an API as a JSON array in componentDidMount method as below.

componentDidMount() {
    return fetch('http://..someAPI../product/')
      .then(res => res.json())
      .then(resJson => {
        this.setState({
          isLoading: false,
          dataSource: resJson,
        });
        var objects = this.state.dataSource;
        for (var i = 0; i < objects.length; i++) {
          console.log('Item Name: ' + objects[i].productName);
        }
      })
      .catch(err => {
        console.log(err);
      });
  }

In here I get console.log output as I want. Now I want to pass the array in a loop as a prop to a custom component, but it gives error. My render method looks like this

return (
      <View>
        <Content>
          {this.state.dataSource.map(item => {
            <Product Name={item.productName} price={item.price}/>;
          })}
        </Content>
      </View>
    );

My original Json object looks like this

[
   {
        "category": [
            "Food",
            "Bread",
            "Bun"
        ],
        "_id": "1",
        "productName": "Sausage bun",
        "price": 70,
        "details": "test product",
    },
    {
        "category": [
            "Food",
            "Bread",
            "Bun"
        ],
        "_id": "2",
        "productName": "Fish Pastry",
        "price": 50,
        "details": "test product",
    }
]

I want to pass these data to display the products as a loop. How can I do this? Thank you in advance!

Since data loading is asynchronous you probably have uninitialised state.

As a safer coding practice you could something like

{this.state.dataSource && this.state.dataSource.map(item => {
            return <Product Name={item.productName} price={item.price}/>;
          })}

Depending on your webpack configuration, you can also use optional chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

{this.state?.dataSource?.map(item => {
            <Product Name={item.productName} price={item.price}/>;
          })}

Also, initialize your state

this.state = {
   dataSource: []
}

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