获取Axios.get()数据并将其显示在React组件中



我在表中通过React组件显示数据时遇到问题。

目标:在React组件中显示MongoDB数据,并了解为什么这个数据过程不起作用。

这里出了什么问题?我知道这不是HTTP请求,所以数据格式似乎是个问题。

供参考:

HTTP请求

app.get('/api/people/fetchall', requireLogin, async (req, res) => {
const userContacts = await User.findOne({_id: req.user._id}, 'contacts');
res.send(userContacts['contacts']);
console.log(userContacts['contacts']);
});

联系人HTTP POST

app.post('/api/people/add', requireLogin, async (req, res) => {
console.log(req.body.name);
const { name, company, linkedin, department, email } = req.body;
const newcontact = new AddContact({
_user: req.user.id,
name: name,
company: company,
linkedin: linkedin,
department: department,
email: email,
dateUpdated: Date.now()
});
User.findByIdAndUpdate(
{_id: req.user._id},
{$push: {contacts: newcontact}},
{safe: true, upsert: true},
function(err, model) {
console.log(err);
}
);
//Our user to add Contact to, and find the contacts array
const user = await req.user.save();
});

React组件,以及组件内的加载数据

import React, {Component} from 'react';
import MaterialTable from 'material-table';
import axios from 'axios';
const fakedata = [{'name': 'Elliot Kang','company': 'Employableh','linkedin': 'linkedin.com/en/elliotkang7',
'department': 'PM','email': 'elliot@employableh.com'}, {'name': 'Elliot Kon','company': 'Employableh','linkedin': 'linkedin.com/en/elliotkang7',
'department': 'PM','email': 'elliot@employableh.com'}];
class ContactDisplay extends Component {
constructor() {
super();
this.state= {contacts: {},
columns: [
{title: 'Name', field: 'name'},
{title: 'Company', field: 'company'},
{title: 'Linkedin', field: 'linkedin'},
{title: 'Department', field: 'department'},
{title: 'Email', field: 'email'}
],
}
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
componentDidMount() {
axios.get('/api/people/fetchall').then(res => {
console.log(res.data);
this.setState({contacts: res.data});
});
}

render() {
return(
<MaterialTable
title='Contacts'
columns = {this.state.columns}
data = {fakedata}
/>
);

}
}
export default ContactDisplay;

我认为问题可能是您忘记更改

data = { fakedata }

data = { this.state.contacts }

在渲染方法中。

所以你需要做两件事…

  1. 将res.send(userContacts['contacts'](更改为res.json(userContacts['contacts](,因为.send用于文本而非json
  2. 所以你在组件中传递fakedata,而应该传递this.state.contacts,并在初始化状态时传递fakedata,所以不要传递contacts:{}do contacts:fakedata

最新更新