gpt4 book ai didi

javascript - 有什么方法可以像 AngularJS 一样在 ReactJS 中获取数据后渲染 DOM 吗?

转载 作者:行者123 更新时间:2023-11-28 05:01:05 25 4
gpt4 key购买 nike

在 AngularJS 中,只要作用域变量发生变化,它就会自动更改 DOM。此外,如果从 ajax 调用获取数据存在延迟,它将在获取数据后呈现。 ReactJS 有没有办法解决此类问题?

我尝试了下面的代码,但它总是显示“正在加载...”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>;
}
}

最佳答案

您遇到此问题的原因是您正在使用 props 来检查帖子

const { posts } = this.props;

这始终为空,因为您没有填充此帖子芽状态的 Prop 因此将该行更改为:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com