我正在尝试映射一个数组,即静态 json 数据。无法映射,因为 this.props.movies.map 不是函数,我收到错误消息。下面是带有 App.js 的 Table 组件的代码。因为 json 文件中的对象是 movies.as 我按照相同的步骤获取 api 但能够获取数据
从'../src/data.json'导入数据
class App extends Component {
constructor(props) {
super(props)
this.state = {
movies: data,
}
}
render() {
return (
<div className="App">
<Header />
<Table movies={this.state.movies} />
</div>
);
}
}
表格.js
import React, { Component } from 'react';
import './Table.css';
import { list } from 'postcss';
class Table extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
const list = this.props.movies.map((movie) => (
<tr key={movie.Title}>
<td>{movie.Title}</td>
<td>{movie.Director}</td>
</tr>
)
);
return (
<div className="table">
table
<table>
<thead>
<tr>
<th>Title</th>
<th>Director</th>
</tr>
</thead>
<tbody>
{list}
</tbody>
</table>
</div>
);
}
}
export default Table;
最佳答案
问题是您的数据包含电影数组。所以在初始化state的时候需要将data.movies赋值给movies。检查下面的一个以便更好地理解
class App extends Component {
constructor(props) {
super(props)
this.state = {
movies: data.movies,
}
}
render() {
const { movies } = this.state;
return (
<div className="App">
<Header />
{movies.length === 0 ? <h1>Loading Movies</h1> : <Table movies={this.state.movies} />}
</div>
);
}
}
关于javascript - 在 React 应用程序中映射对象数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52015179/