我正在尝试使用axios在Al React Flux应用程序中发出Ajax请求,并在设置状态后获取数据。
我在root app中有这个代码:
InitialData.getInitialPosts();
API请求如下所示:
let PostsApi = {
getAllPosts(){
return axios.get('https://jsonplaceholder.typicode.com/posts')
.then( (response) => {
console.log('All posts: ', response.data)
return response.data;
});
}
}
export default PostsApi;
在actions / initialData.js中我有这个:
let LoadInitialData = {
getInitialPosts(){
Dispatcher.dispatch({
actionType: 'LOAD_INITIAL_POSTS',
initialPosts: {
posts: PostsApi.getAllPosts()
}
})
}
}
export default LoadInitialData;
在店内:
let _posts = [];
const PostsStore = Object.assign({}, EventEmitter.prototype, {
addChangeListener(callback){
this.on('change', callback)
},
removeChangeListener(callback){
this.removeChangeListener('change', callback)
},
emitChange(callback){
this.emit('change', callback)
},
getAllPosts(){
return _posts;
}
});
Dispatcher.register(function(action){
switch(action.actionType){
case 'LOAD_INITIAL_POSTS':
_posts = action.initialPosts.posts;
PostsStore.emitChange();
break;
default:
}
});
在视图中:
export default class PostsPage extends React.Component {
constructor(){
super();
this.state = {
posts: []
}
}
componentDidMount(){
this.setState({
posts: PostsStore.getAllPosts()
});
}
render(){
const { posts } = this.state;
return(
<div>
{posts.map( post => {
return <h3 key={post.id}>{post.title}</h3>
})}
</div>
)
}
}
在console.log上:
state:Object {posts:Array [0]}
state:Object {posts:Promise}
postsApi.js:7所有帖子:[对象,对象,对象,对象,对象,对象...]
问题是ajax请求是在componentDidMount
之后。
答案 0 :(得分:1)
您的PostsPage
组件未正确设置以侦听商店中的更改。您拥有的代码只会在首次安装时获取一次的帖子列表。您希望它在Store获取新数据时进行更新。
要完成此操作,您需要使用在商店中设置的添加/删除更改侦听器功能。看起来应该是这样的;
export default class PostsPage extends React.Component {
constructor(){
super();
this.state = {
posts: []
}
}
_calculateState(){
this.setState({
posts: PostsStore.getAllPosts()
});
}
componentDidMount(){
PostsStore.addChangeListener(this._calculateState);
},
componentWillUnmount(){
PostsStore.removeChangeListener(this._calculateState);
},
render(){
const { posts } = this.state.posts;
return(
<div>
{posts.map( post => {
return <h3 key={post.id}>{post.title}</h3>
})}
</div>
)
}
}