Javascript 如何使用ReactJS获取数组或json对象

Javascript 如何使用ReactJS获取数组或json对象,javascript,node.js,reactjs,express,mern,Javascript,Node.js,Reactjs,Express,Mern,我正在使用MERN堆栈,我是一个初学者。我的express应用程序在端口3001上运行,这是我的dbconn路由。它成功地提取了查询,如果我导航到“localhost:3001/dbconn”,它将显示docs数组 const mongoose=require('mongoose')) const MongoClient=require('mongodb')。MongoClient; const express=require('express'); const router=express.

我正在使用MERN堆栈,我是一个初学者。我的express应用程序在端口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://:@wager0 mhodf.mongodb.net/test?retryWrites=true&w=mailty';
const client=new MongoClient(uri,{useUnifiedTopology:true,useNewUrlParser:true});
router.get('/',函数(req,res,next){
res.header('Access-Control-Allow-Origin','*');
//连接到数据库
client.connect(err=>{
log(“已成功连接到服务器”);
//导航到更正
const collection=client.db(“wager0”).collection(“游戏类型”);
//获取数据库中的所有行
collection.find().toArray(函数(err,docs){
res.send(文档);
});
client.close();
});
});

module.exports=路由器你几乎接近了。只需在promise resolve中登录控制台,并使用模板中的状态即可。像这样:

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;
import React,{Component}来自'React';
类测试扩展了组件{
建造师(道具){
超级(道具);
this.state={gameTypes:[]};
}
异步组件didmount(){
取('http://localhost:3001/dbconn', {
标题:{
“内容类型”:“应用程序/json”
}
})。然后(res=>{
this.setState({gameTypes:res});
log(this.state.gameTypes);
});
}
render(){
返回(
游戏类型
{this.state.gameTypes.map(gameType=>(
{gameType.name}
))}
);
}
}
导出默认测试;
//依赖项
从“React”导入React,{Component};
类测试扩展了组件{
建造师(道具){
超级(道具);
this.state={gameTypes:[]};
}
componentDidMount(){
取('http://localhost:3001/dbconn', {
标题:{
“内容类型”:“应用程序/json”
}
}).then(res=>res.json())
.then(data=>this.setState({gameTypes:data}));
log(this.state.gameTypes);
}
渲染(){
报税表(
游戏类型
测试
)
}
}

导出默认测试获取是异步进行的,因此您不应该期望在
componentDidMount
lifecyclehook中设置您的状态。如果您想看到您的状态正在更新,请将状态记录在
componentdiddupdate
hook:
componentdiddupdate(){console.log(this.state.gameTypes)}
Nick,我需要在安装组件时获取数组。我注意到,在启动服务器并导航到路由时,我的dbconn文件会将数据加载到一个数组中,但是任何后续的访问都会提取一个空数组。知道吗?我应该用状态变量来存储这种数据吗?我读到状态变量不应该包含对象,应该保持简单。我拉取这些数据来创建表单的动态下拉列表。你们会建议采取另一种方法吗?状态变量可以容纳对象,并且并没有任何错误。记住javascript对象是引用类型,所以在操作它时一定要小心。