我将React Js用作前端,而node表示为后端。当我使用npm start
启动前端时,它运行时没有错误,但是当我也启动后端时,也会抛出此错误:TypeError: Cannot read property 'map' of undefined
,为此我找不到任何解决方案。
这是错误所在的代码:
import React, { Component } from 'react'
import ApiService from "../../service/ApiService";
import SearchField from "./SearchField";
class ListModuleComponent extends Component {
constructor(props) {
super(props)
this.state = {
modules: [],
message: null
}
this.deleteModule = this.deleteModule.bind(this);
this.editModule = this.editModule.bind(this);
this.addModule = this.addModule.bind(this);
this.reloadModuleList = this.reloadModuleList.bind(this);
}
componentDidMount() {
this.reloadModuleList();
}
reloadModuleList() {
ApiService.fetchModules()
.then((res) => {
this.setState({ modules: res.data.result })
});
}
deleteModule(moduleId) {
ApiService.deleteModule(moduleId)
.then(res => {
this.setState({ message: 'Delete successful.' });
this.setState({ modules: this.state.modules.filter(module => module.id !== moduleId) });
})
}
editModule(id) {
window.localStorage.setItem("moduleId", id);
this.props.history.push('/edit-module');
}
addModule() {
window.localStorage.removeItem("moduleId");
this.props.history.push('/add-module');
}
render() {
return (
<div>
<h2 className="text-center">Modul data</h2>
<button className="btn btn-danger" style={{ width: '100px' }} onClick={() => this.addModule()}>Add</button>
<SearchField />
<table className="table table-striped">
<thead>
<tr>
<th className="hidden">Id</th>
<th>Id</th>
<th>Name</th>
{/* <th>Key</th> */}
<th>Default value</th>
<th>Description</th>
<th>State</th>
</tr>
</thead>
<tbody>
{
this.state.modules.map( // Error throws on this line //
module =>
<tr key={module.id}>
<td>{module.moduleName}</td>
<td>{module.moduleDefaultValue}</td>
<td>{module.description}</td>
<td>{module.isActive}</td>
<td>
<button className="btn btn-success" onClick={() => this.deleteModule(module.id)}> Delete</button>
<button className="btn btn-success" onClick={() => this.editModule(module.id)} style={{ marginLeft: '20px' }}>Edit</button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
);
}
}
export default ListModuleComponent;
因此,该错误仅在后端启动时显示,并且我不知道它是由后端还是前端引起的,只能看到React前端方面的错误。如果需要,我可以提供更多代码。
模块的默认状态是一个数组,这意味着可以在其上进行映射,因此,如果它不获取任何数据,则该组件将很好地呈现。
this.state = {
modules: [],
message: null
}
启动后端后,重新加载模块方法将模块设置为res.data.result] >>
错误是无法读取未定义的属性'map'。
因此,我认为res.data.result是未定义的。
要修复此检查内容是什么,并确保您要设置的状态是数据数组
似乎是空检查将解决此处的明显问题。
res.result.data
最有可能是undefined
。您可以将状态设置为空数组,以防res.result.data
为undefined
的情况,如下所示: