Node.js 为什么我能';在reactjs中,是否通过属性名访问属性json数据?
我正在尝试使用mongodb和mongoose从数据库中获取数据 我有一个请求功能:Node.js 为什么我能';在reactjs中,是否通过属性名访问属性json数据?,node.js,reactjs,mongodb,mongoose-schema,Node.js,Reactjs,Mongodb,Mongoose Schema,我正在尝试使用mongodb和mongoose从数据库中获取数据 我有一个请求功能: componentDidMount(){ fetch('http://localhost:5000/tweet') .then(function(response) { return response.json(); }) .then(result=>{ this.setState({
componentDidMount(){
fetch('http://localhost:5000/tweet')
.then(function(response) {
return response.json();
})
.then(result=>{
this.setState({
tweetData:JSON.stringify(result)
});
console.log(this.state.tweetData);
});
}
我正在尝试通过console.log显示,没有问题:
但是当我通过属性名访问属性时,console.log显示:null
为什么?
以下是我的后端代码:
app.get('/tweet',(req,res)=>{
tweetData.find((err,data)=>{
if(err){
return res.json({success: false, error: err});
}
return res.json({success: true, data:data});
});
})
您必须
result.data
.then(result=>{
this.setState({
tweetData:result.data
},()=>{
console.log(this.state.tweetData);
);
});
而且
设置状态
是异步的。您可以使用回调函数检查状态更新您必须结果。数据
.then(result=>{
this.setState({
tweetData:result.data
},()=>{
console.log(this.state.tweetData);
);
});
而且
setState
是异步的,您可以使用回调函数检查状态更新您正在解析JSON,然后再次对其进行字符串化。删除JSON.stringify
,它应该可以正常工作
setState
也是异步的,因此您不能在它下面的语句中访问新状态。您可以使用setState
的第二个参数,这是一个在设置状态时调用的回调
componentDidMount() {
fetch('http://localhost:5000/tweet')
.then(response => response.json())
.then(result => {
this.setState({
tweetData: result
}, () => console.log(this.state.tweetData));
})
}
您正在解析JSON,然后再次对其进行字符串化。删除
JSON.stringify
,它应该可以正常工作
setState
也是异步的,因此您不能在它下面的语句中访问新状态。您可以使用setState
的第二个参数,这是一个在设置状态时调用的回调
componentDidMount() {
fetch('http://localhost:5000/tweet')
.then(response => response.json())
.then(result => {
this.setState({
tweetData: result
}, () => console.log(this.state.tweetData));
})
}