javascript - 为什么 React 没有渲染我的地图功能?
问题描述
我有一个映射函数到一个状态,我确定它不是空的,因为它的状态已被记录。
当我加载页面时,它显示 div“加载了”,但仅此而已。控制台也不会注册他的“运行”日志。
这是针对 CS50W 课程的,所以我使用的是浏览器内的 Babel 转换器。有人建议我完全改变编译代码的方法,但这意味着学习并进行全新的设置,所以我希望这不是它不起作用的原因。
class Posts extends React.Component{
constructor(props){
super(props)
this.state = {
aposts: [],
isLoaded: false
}
}
componentDidMount() {
console.log('running go fetch');
let currentList = [];
fetch('/posts')
.then(response => response.json())
.then(posts => {
for (var i = 0; i < posts.length; i++) {
currentList.push(posts[i])
console.log(currentList[i])
}
});
console.log(currentList)
this.setState({ aposts: currentList, isLoaded: true }, () => {
console.log(this.state.aposts, 'aposts');
});
}
render(){
var isLoaded = this.state.isLoaded
if (isLoaded = true){
return (
<div>
<div>did load</div>
{this.state.aposts.map(function(apost) {
console.log("running")
return (<li key = {apost.id}> {apost.id} </li>)
})}
</div>
);
}
else{
<div>No load</div>
}
}
解决方案
componentDidMount() {
console.log('running go fetch');
let currentList = [];
fetch('/posts')
.then(response => response.json())
.then(posts => {
for (var i = 0; i < posts.length; i++) {
currentList.push(posts[i])
console.log(currentList[i])
}
console.log(currentList)
this.setState({ aposts: currentList, isLoaded: true }, () => {
console.log(this.state.aposts, 'aposts');
});
});
进行 api 调用时需要一些时间,因此 JS 只需在其他进程上运行该工作,您的主进程就会继续工作。
阅读有关同步/异步的信息
当你使用.then
它时,当 JS 完成 api 调用并从服务器获取响应时,它应该运行里面的任何东西.then
所以你必须设置状态,.then
所以它会在它获取值后为状态设置值
你说你必须设置并学习设置。你为什么不使用 [CRA][1] 它会为你设置一切。
推荐阅读
- javascript - Heroku 给了我一个 CORS 问题,但仅在部署 20 分钟后。在此之前,一切正常
- dart - 参数类型“字符串”不能分配给参数类型“对象?函数(对象?,对象?)?
- networking - GRPC 上的全双工
- swift - 如何分享领域结果
到其他视图? - javascript - Node JS 服务器运行但不工作,我能做什么?
- node.js - 如何覆盖在 Node js 控制器函数中定义的函数的测试用例覆盖率
- python - curve_fit 的快速 Python 指数函数:Numpy Express 给出较慢的结果
- c# - C# 代码长度和性能之间是否存在依赖关系?
- python - href 不能将我转移到 html 页面?
- python - 通过使用不在 python 中工作的代理来更改 IP?