gpt4 book ai didi

javascript - 在 React 组件构造函数中处理 promise 链

转载 作者:行者123 更新时间:2023-11-29 23:27:59 25 4
gpt4 key购买 nike

我正在从我的 API 中获取数据,并且需要根据接收到的数据构建一个列表。问题是,渲染发生在构造函数中的提取完成之前,因此发送到 List 组件的 this.todo 恰好是空的。处理此问题的正确方法是什么?

import React, { Component } from 'react';
import {render} from 'react-dom';
import Header from './header.jsx'
import List from './list.jsx'

class App extends Component {
constructor(props) {
super(props)
this.todos = []

const url = "http://localhost:3000/api/todos/"
fetch(url)
.then(res => res.json())
.then((data) => {
this.todos = data;
})
.catch(console.error);
}

render () {
return (
<div>
<Header />
<List tasks={this.todos}/>
</div>
)
}
}

render(<App/>, document.getElementById('app'));

最佳答案

您通常希望向用户发出数据正在加载的信号。您还希望确保区分空数据和未收到的数据。

您还希望此数据成为组件状态的一部分,而不是类实例本身,以允许组件在收到数据时重新呈现。

=> this.state.todos 而不是 this.todos

class Example extends React.Component {
constructor(props) {
super(props)
this.state = {
todos: null
}
setTimeout(() => {
this.setState({
todos: [1,2,3]
})
}, 1000);
}

render () {
return (
<div>
{this.state.todos
? <div>{this.state.todos.toString()}</div>
: <div>Loading todos...</div>
}
</div>
)
}
}

ReactDOM.render(<Example/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

这里还有许多其他改进。您可以潜在地缓存数据并在以后显示它,而无需从网络中获取它,然后您可以在幕后获取任何新数据。如果微调器不起作用,您或许可以使用某种占位符。这完全取决于数据的类型、数据的持久性、用户与之交互的程度、数据更改的程度等。

关于javascript - 在 React 组件构造函数中处理 promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48362371/

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