[英]how do i import and use promise function on my react component?
所以這是我的 movies.js 組件,我想將數據電影傳遞給我想在卡上顯示數據的其他組件,但我不知道如何使用 promise function:
const movies = [
{
id: '1',
title: 'Oceans 8',
category: 'Comedy',
likes: 4,
dislikes: 1
}, {
id: '2',
title: 'Midnight Sun',
category: 'Comedy',
likes: 2,
dislikes: 0
},
]
export const movies$ = new Promise((resolve, reject) => setTimeout(resolve, 100, movies))
這是我想在卡片上顯示的另一個組件,我嘗試導入 const movie$ 但它不起作用:
import React, { Component } from "react";
import { Card, Button } from "react-bootstrap";
import { movies$ } from "../Data/movies";
export default class Movies extends Component {
render() {
return (
<div>
<h1>Movies</h1>
<Card style={{ width: "18rem" }}>
<Card.Img variant="top" src="holder.js/100px180" />
<Card.Body>
<Card.Title>
<movies$
/>
</Card.Title>
<Card.Text>
Some quick example text to build on the card title and make up the
bulk of the card's content.
</Card.Text>
<Button variant="primary">Supprimer</Button>
</Card.Body>
</Card>
</div>
);
}
}
您需要在組件state
中創建一個屬性來存儲電影,然后在解析Promise
時填充它:
import { movies$ } from "../Data/movies";
export default class Movies extends Component {
constructor() {
this.state = {
movies: []
}
}
componentDidMount() {
movies$
.then(data => this.setState({movies: data}))
}
//...
}
遍歷電影以渲染數據:
IE:
<Card.Title>
{this.state.movies.map(movie => (<div>{movie.title}</div>))}
</Card.Title>
您不需要 promise。 要顯示數組中的數據,請使用 map() function
電影.js
const movies = [
{
id: "1",
title: "Oceans 8",
category: "Comedy",
likes: 4,
dislikes: 1
},
{
id: "2",
title: "Midnight Sun",
category: "Comedy",
likes: 2,
dislikes: 0
}
];
export default movies;
應用程序.js
import React, { Component } from "react";
import { Card, Button } from "react-bootstrap";
import movies from "./movies";
export default class Movies extends Component {
render() {
return (
<div>
<h1>Movies</h1>
{/* map function below */}
{movies.map(movie => (
<Card key={movie.id} style={{ width: "18rem" }}>
<Card.Img variant="top" src="holder.js/100px180" />
<Card.Body>
<Card.Title>{movie.title}</Card.Title>
<Card.Text>
Some quick example text to build on the card title and make up
the bulk of the card's content.
</Card.Text>
<Button variant="primary">Supprimer</Button>
</Card.Body>
</Card>
))}
</div>
);
}
}
演示: stackblitz
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.