【问题标题】:How to fetch array or json objects using ReactJS如何使用 ReactJS 获取数组或 json 对象
【发布时间】:2019-12-14 23:44:19
【问题描述】:

我正在使用 MERN 堆栈并且是初学者。我的快速应用程序在端口 3001 上运行,这是我的 dbconn 路由。它成功提取查询,如果我导航到“localhost:3001/dbconn”,它会显示 docs 数组。

const mongoose = require('mongoose')
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const router = express.Router();
const uri ='mongodb+srv://<user>:<password>@wager0-mhodf.mongodb.net/test?retryWrites=true&w=majority';
const client = new MongoClient(uri, { useUnifiedTopology: true, useNewUrlParser: true });

router.get('/', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');

  //Connect to db
  client.connect(err => {
      console.log("Connected successfully to server");
      //navigate to correction
      const collection = client.db("wager0").collection("gameTypes");
      //Get all rows in db
      collection.find().toArray(function(err, docs) {
        res.send(docs);
      });
      
    client.close();
  });
});

module.exports = router;

但是,当我尝试在我的 react 应用程序中获取这个数组时,它只是在拉一个空数组。下面是我的测试组件的代码,然后在客户端(反应)应用程序的 app.js 文件中呈现。我真正需要做的是创建一个包含所有可用游戏类型的下拉列表,但会满足于能够获取数组。

// Dependencies 
import React, {Component} from 'react';

class Test extends Component{
    constructor(props){
        super(props);
        this.state = {gameTypes: []};
    }
    componentDidMount(){
        fetch('http://localhost:3001/dbconn', {
            headers: {
            'Content-Type': 'application/json'
            }
        })
            .then(res =>  this.setState({gameTypes: res}));
        console.log(this.state.gameTypes);    
    }

    render (){
        return( 
            <div className="GameTypes">
                <h1>Game Types</h1>
                <div>
                    <select>
                        <option>test</option>
                    </select>
                </div>
            </div>
        )
    }
}

export default Test;

【问题讨论】:

  • 你的获取是异步发生的,所以你不应该期望在componentDidMount生命周期钩子中设置你的状态。如果您想看到您的状态正在更新,请将状态记录在 componentDidUpdate 挂钩中:componentDidUpdate(){ console.log(this.state.gameTypes) }
  • 尼克,我需要在安装组件时获取数组。我怎样才能做到这一点?

标签: javascript node.js reactjs express mern


【解决方案1】:

你几乎接近。只需在 Promise 中进行控制台日志解析并使用模板中的状态。像这样:

import React, { Component } from 'react';

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = { gameTypes: [] };
  }
  async componentDidMount() {
    fetch('http://localhost:3001/dbconn', {
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => {
      this.setState({ gameTypes: res });
      console.log(this.state.gameTypes);
    });
  }

  render() {
    return (
      <div className="GameTypes">
        <h1>Game Types</h1>
        <div>
          <select>
            {this.state.gameTypes.map(gameType => (
              <option>{gameType.name}</option>
            ))}
          </select>
        </div>
      </div>
    );
  }
}

export default Test;

【讨论】:

  • 我注意到我的 dbconn 文件会在启动服务器并导航到路由时将数据加载到数组中,但是任何后续访问都会拉出一个空数组。有什么想法吗?
【解决方案2】:

// Dependencies 
import React, {Component} from 'react';

class Test extends Component{
    constructor(props){
        super(props);
        this.state = {gameTypes: []};
    }
    componentDidMount(){
        fetch('http://localhost:3001/dbconn', {
            headers: {
            'Content-Type': 'application/json'
            }
        }).then(res => res.json())
          .then(data =>  this.setState({gameTypes: data}));
        console.log(this.state.gameTypes);    
    }

    render (){
        return( 
            <div className="GameTypes">
                <h1>Game Types</h1>
                <div>
                    <select>
                        <option>test</option>
                    </select>
                </div>
            </div>
        )
    }
}

export default Test;

使用上面的 sn-p 更改您的代码。在 react 中使用 fetch api 时,您需要先将响应转换为 JSON,然后再编写 .then 函数。在第二个 .then 函数中,您将获取数据。

在 setState() 之后不要使用 console.log() 检查状态值,因为 react 的 setState 方法是异步的。

【讨论】:

  • 我应该使用状态变量来存储这种数据吗?我读到状态变量不应该包含对象,并且应该保持简单。我正在提取这些数据以创建表单的动态下拉列表。你会建议采取不同的方法吗?
  • 状态变量可以保存对象,我没有错。请记住 javascript 对象是一种引用类型,所以在操作它时要小心。
猜你喜欢
  • 2016-12-25
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多