2017-10-07 52 views
0

我回來的json響應調用status看起來像這樣。嘗試映射對象數組時,React未能編譯

{map: "TheIsland", password: false, raw: {…}, maxplayers: 30, …}players:[{…}]".... 

我試圖映射玩家屬性爲單個JSX元素的當前名稱,但.map返回錯誤

TypeError: Cannot read property 'map' of undefined" when applied to "props.status.players

我懷疑這是因爲組件之前fetchStatus()回報與裝status,因此.map正在undefined屬性players上運行。我添加了constructor,但現在React由於語法錯誤而無法編譯。

import React, { Component } from "react"; 
import { connect } from "react-redux"; 
import { fetchStatus } from "./../actions"; 

import "./arkStats.css"; 

class ArkStats extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
    players: [] 
    }; 
} 
    componentDidMount() { 
    this.props.fetchStatus(); 
    } 

    renderPlayers() { 
    return (
     <div> 
     {this.props.status.players.map((players, index) => 
      <p key={index}> 
      Hello, {players.name}! 
      </p> 
     )} 
     </div> 
    ); 
    } 

    render() { 
    return (
     <div> 
     {this.props.status.name} 
     {this.props.status.map} 
     {this.renderPlayers()} 
     </div> 
    ); 
    } 
} 

function mapStateToProps({ status }) { 
    return { status }; 
} 

export default connect(mapStateToProps, { fetchStatus })(ArkStats); 

感謝您對我的構造函數的修復!然而,當「.map」在「status.players」上執行時,這並沒有改變我得到的響應。 (說它仍然是未定義的。)當控制檯登錄Chrome時,出現這種情況。

players: Array(3) 
0:{name: "Jones", score: 0, time: 1573.2921142578125} 
1:{name: "Matt", score: 0, time: 1348.6531982421875} 
2:{name: "Skippy", score: 0, time: 285.5899963378906} 
length:3 

回答

0

因此,首先,你不使用this.setState在構造函數中,你剛纔說this.state = {...}

其次,其原因可能是因爲像你說的「玩家」值是不確定的部件首先當坐騎。所以,簡單地在renderPlayers()功能添加一個支票本,即

If 'players' value exists, return a map of it, else return null 
0

你是對的,players不是數組,直到你的API調用完成,這就是爲什麼你需要初始化的狀態你的反應成分爲它處理第一個渲染。

像這樣:

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

的語法錯誤是由這一行// {this.renderPlayers()}comments in JSX引起像Javascript代碼塊註釋和它們必須被包裹在大括號({ /* {this.renderPlayers() */ })。

你似乎也有一個額外的大括號:因爲你在你的構造函數,並在構造函數中不能使用的setState代替初始化狀態有額外的大括號「}」

​​
0

語法錯誤。 所以你的構造將是

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

而且在構造

constructor(props){ 
     super(props); 
     this.setState({players: []}); 
    } // This one 
    } 

引起語法錯誤的,因爲額外}您可以註釋代碼裏面JSX應該從// {this.renderPlayers()}改爲{/*this.renderPlayers()*/}