我回來的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