在 React 中使用 Fetch 渲染列表
尝试从随机 API 呈现电影列表并最终过滤它们.
componentDidMount() {var myRequest = 新请求(网站);让电影 = [];获取(我的请求).then(function(response) { return response.json(); }).then(函数(数据){data.forEach(电影 =>{电影.push(电影.title);})});this.setState({movies: movies});}使成为() {控制台.log(this.state.movies);console.log(this.state.movies.length);返回 (<h1>电影列表</h1>)}
如果我渲染它,我只能打印我的状态而不能访问里面的内容.我将如何创建 LI 列表并呈现 UL?谢谢
解决方案一些事情.fetch
是异步的,因此您实际上只是在编写时将电影设置为一个空数组.如果 data
是一个电影数组,你可以直接在你的状态中设置它,而不是先将它复制到一个新数组中.最后,在 Promise 中使用箭头函数作为最终回调将允许您使用 this.setState
而无需显式绑定函数.
最后,您可以使用 JSX 花括号语法来映射状态对象中的电影,并将它们呈现为列表中的项目.
class MyComponent 扩展 React.Component {构造函数(){极好的()this.state = {电影:[]}}组件DidMount() {var myRequest = 新请求(网站);让电影 = [];获取(我的请求).then(response => response.json()).then(数据 => {this.setState({电影:数据})})}使成为() {返回 (<h1>电影列表</h1><ul>{this.state.movies.map(movie => {return <li key={`movie-${movie.id}`}>{movie.name}</li>})}</ul></div>)}}
Trying to render a list of movies from a random API and eventually filter them.
componentDidMount() {
var myRequest = new Request(website);
let movies = [];
fetch(myRequest)
.then(function(response) { return response.json(); })
.then(function(data) {
data.forEach(movie =>{
movies.push(movie.title);
})
});
this.setState({movies: movies});
}
render() {
console.log(this.state.movies);
console.log(this.state.movies.length);
return (
<h1>Movie List</h1>
)
}
If I render this I can only print my state and not access what is inside. How would I create a list of LIs and render a UL? Thanks
解决方案A few things. fetch
is asynchronous, so you're essentially just going to be setting movies to an empty array as this is written. If data
is an array of movies, you can just set that directly in your state rather than copying it to a new array first. Finally, using an arrow function for the final callback in the promise will allow you to use this.setState
without having to explicitly bind the function.
Finally, you can use JSX curly brace syntax to map over the movies in your state object, and render them as items in a list.
class MyComponent extends React.Component {
constructor() {
super()
this.state = { movies: [] }
}
componentDidMount() {
var myRequest = new Request(website);
let movies = [];
fetch(myRequest)
.then(response => response.json())
.then(data => {
this.setState({ movies: data })
})
}
render() {
return (
<div>
<h1>Movie List</h1>
<ul>
{this.state.movies.map(movie => {
return <li key={`movie-${movie.id}`}>{movie.name}</li>
})}
</ul>
</div>
)
}
}
相关文章