簡體   English   中英

獲取 Axios.get() 數據並在 React 組件中顯示

[英]Taking Axios.get() data and displaying it in React component

我無法通過表格中的 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 並在初始化 state 時傳遞 fakedata 所以而不是聯系人:{} 做聯系人:fakedata

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM