【发布时间】:2016-03-01 19:47:48
【问题描述】:
我有一个 react 组件,它在构造函数方法中以空白默认状态开始。 当 componentDidMount 我想用我通过 AJAX 从我的 API 获得的东西来更新状态。
这个组件的代码如下:
import React from 'react';
import Header from './Header';
import FeedOwnerColumn from './FeedOwnerColumn';
import FeedColumnRight from './FeedColumnRight';
import ReportBug from './ReportBug';
class FeedApp extends React.Component{
constructor(){
super();
this.addComment = this.addComment.bind(this);
this.componentDidMount = this.componentDidMount.bind(this);
this.state = {
ownerInfo:{},
ownerDogs:[],
ownerApps:[],
ownerChat:{},
posts:[]
}
}
componentDidMount(e){
var that = this;
$.get('/api/getUserInit', function(result) {
console.log(result);
this.setState({
ownerInfo: result.ownerInfo,
ownerDogs: result.ownerDogs,
ownerNotifications: result.ownerNotifications,
ownerChat: result.ownerChat,
posts: result.posts
});
}.bind(this));
}
addComment(e){
e.preventDefault();
var currTime = new Date();
currTime = currTime.toLocaleString();
var commentContent = e.target.childNodes[0].value;
var key = Math.random();
key = Math.round(key);
var newComment = {
id: key,
name: "Peter Paprika",
date: currTime,
thumb_picture:"/imgs/user-q.jpg",
profile_link: "/user/123",
content: commentContent,
like_amount: 0
};
var postsObj = this.state.posts;
//console.log(postsObj[0].comments);
var newComments = postsObj[0].comments;
newComments.push(newComment);
console.log(newComments);
this.setState({posts: postsObj});
}
render() {
return (
<div className="clearfix wrapper">
<Header />
<FeedOwnerColumn />
<FeedColumnRight posts={this.state.posts} addComment={this.addComment} />
<ReportBug />
</div>
);
}
}
export default FeedApp;
不幸的是,componentDidMount 方法中的 this.setState({}) 似乎没有被正确调用,因为没有发生状态更新,而且我的地图函数期望数组无事可做并返回错误。
我想在状态更新中使用的对象如下所示:
ownerChat: Object
ownerDogs: Array[1]
ownerInfo: Object
ownerNotifications: Array[0]
posts: Array[2]
我真的不知道除了这个方法还有什么可以尝试的:/
【问题讨论】:
-
您的
console.log(result)是否产生任何输出?如果是这样,我怀疑有约束力问题。尝试console.log(this)看看this是否指向正确的对象.. -
我将状态作为道具传递给这个组件:
-
@wintvelt 它产生了我在问题底部显示的对象:)
-
或者用
bind(that)代替this? -
按照代码,
render()方法应该被调用两次。它实际上被调用了两次吗?你能在每次调用中console.logthis.state对象吗?
标签: javascript reactjs ecmascript-6