我目前正在reactJS上创建一个新组件,该组件仅需要显示在另一个组件中单击的特定用户的详细信息。但是,我在尝试从后端到前端收集数据时遇到了问题。
以下是显示所有用户列表的组件(consultants.component.js):
sol=minimize(objective,x0,method='SLSQP',constraints=cons,args=(std_dev1,std_dev2,co),bounds=bnds)
当用户单击“所有用户”表中的特定行时,其特定ID将在url中传递,并且该用户还将重定向到另一个组件。 以下是应该显示单击的特定用户的详细信息的组件:
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import './consultants.component.css'
import axios from 'axios';
const Consultant = props => (
<tr>
<td>{props.consultant.employee_name}</td>
<td>{props.consultant.employee_title}</td>
<td>
<NavLink to={'/detail_consultant/'+props.consultant._id}><button className='btn btn-info ml-auto'>details</button></NavLink>
</td>
</tr>
)
export default class ConsultantList extends Component {
constructor(props) {
super(props);
this.state = {consultants: []};
}
componentDidMount() {
axios.get('http://localhost:5000/consultants/')
.then(response => {
this.setState({ consultants: response.data })
})
.catch((error) => {
console.log(error);
})
}
consultantList() {
return this.state.consultants.map(currentconsultants => {
return <Consultant consultant={currentconsultants} key={currentconsultants._id}/>;
})
}
render() {
return (
<div className='consultant-page'>
<h3>List of Consultants</h3>
<table className='table-responsive'>
<thead className='table table-striped'>
<tr>
<th scope='col'>Employee Name</th>
<th scope='col'>Title</th>
<th scope='col'>Actions</th>
</tr>
</thead>
<tbody>
{ this.consultantList() }
</tbody>
</table>
</div>
)
}
}
我已经用失眠测试了get /:id,并且它工作正常,所以问题一定在前端。
Here is the error that I am currently getting
有人可以帮助我找出问题所在吗?
谢谢。
答案 0 :(得分:2)
确保Detail_consultant component
中componentDidmount Lifecycle方法中Axios请求中从后端获取的数据是一个数组。堆栈跟踪表明response.data
不是数组,并且可能是对象,其原型中没有方法.map()
。如果它是一个对象,则将response.data
内的Array定位为处于该状态的集合,所有内容将相应地运行。一个例子是:
componentDidMount() {
axios.get('http://localhost:5000/consultants/' + this.props.match.params.id)
.then(response => {
this.setState({ consultants: response })
})
.catch((error) => {
console.log(error);
})
}