在angularJS中,只要范围变量发生变化,它就会自动更改DOM。同样,如果从ajax调用中获取数据存在延迟,则它将在获取数据后呈现。 ReactJS有什么方法可以解决这种问题?
我试过下面的代码,但它始终显示“ loading ...” div
import React from "react";
import axios from 'axios';
export default class Article extends React.Component {
constructor(props) {
console.log(props);
super(props);
this.state = {
posts: []
};
}
componentDidMount() {
axios.get(`http://www.reddit.com/r/reactjs.json`)
.then(res => {
const posts = res.data.data.children.map(obj => obj.data);
this.setState({ posts });
console.log(posts);
});
}
render() {
const { posts } = this.props;
if (posts) {
const { title } = this.props;
const { articleName } = this.props;
console.log(this.state.posts);
return (
<div className="col-md-4">
<h4>{title}</h4>
<p>This is generated from Article Component from Article JS { title }</p>
<a className="btn btn-default" href="#">More Info</a>
<div>
{posts}
</div>
</div>
);
}
return <div>Loading...</div>;
}
}
最佳答案
您遇到该问题的原因是您正在使用道具检查帖子
const { posts } = this.props;
并且该字段始终为null,因为您没有道具填充此帖子的芽状态
因此将该行更改为:
const posts = this.state.posts;
还在:
if(posts) {
const postList = posts.map((post, index) =>
<div key={index}>post.Title</div>);// Title (if title is part of json)
return (
<div className="col-md-4">
<h4>{title}</h4>
<p>This is generated from Article Component from Article JS { title }</p>
<a className="btn btn-default" href="#">More Info</a>
<div>
{postList}
</div>
</div>
);
}
关于javascript - 有什么方法可以像AngularJS一样在ReactJS中获取数据后呈现DOM?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42131137/