我在显示 JSON 数据时遇到问题。我有一个类,它返回带有 JSON 数据的对象数组。我将此类导入到另一个类中,并尝试通过其返回(JSON 对象数组)进行映射,但它似乎不起作用。
失败并出现错误:
TypeError: this.state.json.map is not a function
这是代码
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 中状态的联系人列表。
所以我的建议是将联系人数据作为 props 传递到 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';
并在渲染方法中使用
<List
contacts={Contacts}
/>
关于javascript - this.state.json.map 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47813632/