【发布时间】: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