2017-10-11 92 views
0

我在我的智慧結尾。我是一個編碼新手,試圖使用.map()遍歷JSON數據並將其顯示在React中的卡上。React無法在setState後使用Fetch提交render

予取componentDidMount下的數據()和使用的setState分配它。這在其他頁面上完全正常。

然而,這一頁我想通過這個對象的「項目」數組迭代,但每當我試圖.MAP()到產品陣列我得到的錯誤上。

即使有一個簡單的console.log我也會收到錯誤。

我認爲這與異步提取,但是我看到解決這一問題用的setState()做。我不知道該怎麼辦。

這裏是我的JSON對象:

{ 
    "_id": "59dac308b9267fbcb5d2de32", 
    "name": "The Jewelry Counter", 
    "description": "Limited edition fine jewelry, handcrafted in the USA", 
    "image": "/public/images/tjclogo.png", 
    "__v": 0, 
    "products": [ 
     { 
      "_id": "59dada32b9267fbcb5d2de37", 
      "name": "Opal and cubic zirconia stacking ring set", 
      "price": 80, 
      "description": "A three ring stacking set that features an arced ring with an opal and cz, one with just glowing cz's and one with a single solitaire prong set opal.", 
      "img": "/shopping-cart-app/public/images/ringset.png", 
      "quantity": 2, 
      "__v": 0, 
      "keywords": [ 
       "ring", 
       "opal", 
       "cubic zirconia", 
       "cz", 
       "jewelry", 
       "womens", 
       "jewelry counter" 
      ] 
     }, 
     { 
      "_id": "59dadae1b9267fbcb5d2de38", 
      "name": "Moonstone Ear Jackets", 
      "price": 140, 
      "description": "Four teardrop shaped glowing moonstones are prong set and attach to your ear in a simple three piece process that makes it look as though they are floating on your ears.", 
      "img": "/shopping-cart-app/public/images/moonearrings.png", 
      "quantity": 4, 
      "__v": 0, 
      "keywords": [ 
       "earrings", 
       "moonstone", 
       "jewelry", 
       "womens", 
       "jewelry counter" 
      ] 
     }, 
     { 
      "_id": "59dadb79b9267fbcb5d2de39", 
      "name": "Horizontal Pyrite Necklace", 
      "price": 52, 
      "description": "A horizontal bar of hand crushed pyrite is attached to a brass bar on a 16\" brass chain.", 
      "img": "/shopping-cart-app/public/images/pyritenecklace.jpg", 
      "quantity": 1, 
      "__v": 0, 
      "keywords": [ 
       "necklace", 
       "pyrite", 
       "jewelry", 
       "womens", 
       "jewelry counter" 
      ] 
     }, 
     { 
      "_id": "59dadcfbb9267fbcb5d2de3a", 
      "name": "Purple Tourmaline Promise Rings", 
      "price": 48, 
      "description": "Faceted purple tourmaline prong set on an 18K yellow gold vermeil band. This simple ring is perfect for stacking.", 
      "img": "/shopping-cart-app/public/images/ring.jpg", 
      "quantity": 1, 
      "__v": 0, 
      "keywords": [ 
       "ring", 
       "tourmaline", 
       "jewelry", 
       "womens", 
       "jewelry counter" 
      ] 
     } 
    ] 
} 

我有以下代碼:

import React, { Component } from 'react'; 
import StoreCard from '../../StoreCard'; 
import ProductCard from '../../ProductCard'; 
import Wrapper from '../../Wrapper'; 
import Header from '../../Header'; 
import StoreLogin from "../../StoreLogin"; 
import Store from "../../Store"; 
import './Shop.css'; 

class Shop extends Component { 

    constructor(props) { 
     super(props); 
     this.state = { storeInfo: []}; 

    } 

    // state = {storeInfo: [], 
     // products: [] 
    // }; 

    componentDidMount() { 
    fetch('/stores/59dac308b9267fbcb5d2de32') 
     .then(res => res.json()) 
     .then((storeInfo) => {this.setState({ storeInfo: storeInfo })}) 
    } 






    render() { 
    console.log(this.state.storeInfo) // works,displays the entire JSON object after beig called twice in the console. 
    console.log(this.state.storeInfo.name); // WORKS, same as above 
    console.log(this.state.storeInfo['products'][1]['name']); //DOES NOT WORK - ERRORS 
    // console.log(this.state.storeInfo.products[1].name); //DOES NOT WORK - ERRORS 

    return (
    <div> 
     <Header location="Search all stores"/> 
     <Wrapper> 

      <StoreLogin 
      id={this.state.storeInfo._id} // works 
      userName={this.state.storeInfo.name} // works 
      // productName={this.state.storeInfo.products[1].name} //does not work 
      > 






      </StoreLogin> 

     </Wrapper> 
     <h1>Shop</h1> 
     </div> 
    ); 
    } 
} 


export default Shop; 

當我去掉了 'console.logs',並在storeLogin成分之一,爲產品名稱一時間,我得到3個錯誤:

Uncaught TypeError: Cannot read property '1' of undefined

然後

proxyConsole.js:54 The above error occurred in the <Shop> component: 
    in Shop (created by Route) 
    in Route (at App.js:22) 
    in div (at App.js:19) 
    in Router (created by BrowserRouter) 
    in BrowserRouter (at App.js:17) 
    in App (at index.js:6) 

Consider adding an error boundary to your tree to customize error handling behavior. 
You can learn more about error boundaries at https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html 

然後

Uncaught TypeError: Cannot read property '1' of undefined

一次。

+0

它拋出了什麼錯誤? – pritesh

+0

爲什麼初始化'storeInfo'作爲空數組,當提取結果在一個單一的對象? –

+0

@pritesh我更新了我的原始問題以顯示我的錯誤,謝謝你的時間! – kittyhawk

回答

0

原因是你試圖訪問的數據storeInfo ['products'] [1] ['name']在渲染函數中最初還沒有提供。所以你需要檢查數據是否存在。你能做的就是

render() { 
    console.log(this.state.storeInfo.name); // WORKS 

    //Move this console inside if 
    if (this.state.storeInfo.products && this.state.storeInfo.products.length) { 
     console.log(this.state.storeInfo['products'][1]['name']); 
     console.log(this.state.storeInfo.products[0].name); 
    } 

    return (
    <div> 
     <Header location="Search all stores"/> 
     <Wrapper> 

     <StoreLogin 
      id={this.state.storeInfo._id} // works 
      userName={this.state.storeInfo.name} // works 
      productName={this.state.storeInfo.products && this.state.storeInfo.products.length && 
this.state.storeInfo.products[0].name} //<-- Same here 
     > 
     </StoreLogin> 
    </Wrapper> 
    <h1>Shop</h1> 
    </div> 
    ); 
} 
+0

Pritesh!你是一個救星!這工作。無論如何將它放入.map()方法中?像'{this.state.storeInfo.products.map(產品)=>}' – kittyhawk

+0

haha​​..Thanks ... – pritesh

+0

是的,你可以像這樣'this.state.storeInfo.products.map((產品)=>)' – pritesh

0

的問題是,你是在componentDidMount功能有fetchRequest,然後設置狀態,但渲染之前就打來電話,因爲您嘗試訪問this.state.storeInfo.products[0].namethis.state.storeInfo.products是不確定的,因此,你會得到一個錯誤,請檢查使用它

return (
<div> 
    <Header location="Search all stores"/> 
    <Wrapper> 

     <StoreLogin 
     id={this.state.storeInfo._id} // works 
     userName={this.state.storeInfo.name} // works 
     productName={this.state.storeInfo.products && his.state.storeInfo.products[0]? 
     this.state.storeInfo.products[0].name: ''} 
     > 
前0
+0

謝謝Shubham,這讓我的代碼工作! – kittyhawk

+0

很高興幫助。請考慮接受答案 –