[英]this.state.json.map is not a function
我在顯示JSON數據時遇到問題。 我有一個返回帶有JSON數據的對象數組的類。 我將此類導入另一個,並嘗試通過其返回值(JSON對象數組)進行映射,但它似乎不起作用。
它失敗並顯示以下錯誤:
TypeError:this.state.json.map不是函數
這是代碼
Contact.js
import React, { Component } from 'react';
export default class Contact extends Component {
render () {
return [
{
"name" : "Alex",
"number" : "088217821878",
},
{
"name" : "Rosie",
"number" : "087627627132",
}
];
}
}
List.js
import React, { Component } from 'react';
import Contact from './Contact';
class List extends Component {
constructor(props) {
super(props)
this.state = {
json: []
}
}
componentDidMount() {
this.setState((prevState) => {
return {
json: Contact
}
})
}
render() {
return (
<div>
<table class="table is-bordered is-hoverable">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
{this.state.json.map((data, i) => {
return (
<tr key={i}>
<td>{data.name}</td>
<td>{data.number}</td>
</tr>
)
})}
</tbody>
</table>
</div>
);
}
}
export default List;
問題是您將數據和可視組件混合在一起。
我想起初,您不需要在List.js中處於狀態的聯系人列表。
所以我的建議是將聯系數據作為道具傳遞到List.js中。
因此,將聯系人數據定義為const,或者如果您使用狀態機(例如Redux)為此創建存儲。
Contact.js
export const Contacts =[
{
"name" : "Alex",
"number" : "088217821878",
},
{
"name" : "Rosie",
"number" : "087627627132",
}
];
List.js
import React, { Component } from 'react';
class List extends Component {
render() {
return (
<div>
<table class="table is-bordered is-hoverable">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
{this.props.contacts.map((data, i) => {
return (
<tr key={i}>
<td>{data.name}</td>
<td>{data.number}</td>
</tr>
)
})}
</tbody>
</table>
</div>
);
}
}
export default List;
比在父組件中將其用作
import { Contacts } from './Contact';
並在render方法中使用
<List
contacts={Contacts}
/>
您不應該真正使用組件那樣返回JSON,因此這是另一種方法。
將聯系人JSON作為文件存儲在本地:
{
"contacts": [
{
"name": "Alex",
"number": "088217821878"
},
{
"name": "Rosie",
"number": "087627627132"
}
]
}
然后,您應該能夠直接將聯系人導入列表組件並將其存儲在您的狀態中。
import React, { Component } from 'react';
import { contacts } from './contacts.json';
class List extends Component {
constructor() {
super();
this.state = { contacts }
}
render() {
return (
<div>
<table class="table is-bordered is-hoverable">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
{this.state.contacts.map((data, i) => {
return (
<tr key={i}>
<td>{data.name}</td>
<td>{data.number}</td>
</tr>
)
})}
</tbody>
</table>
</div>
);
}
}
export default List;
但是,正如@Ivan Mjartan所建議的那樣,您可能要考慮在父組件中導入聯系人列表,並將數組作為屬性向下傳遞給List
。
<List contacts={contacts} />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.