这里有一段函数只是将React中的元素命名为box的道具。在这个MovieDatabase
是一个JSON文件,其中包含不同电影的标题。我只想看那些名字包含“星球大战”的电影。
const showMovies = MovieDatabase.map((movie) =>{
const aa = movie.title.contains("Star Wars")
return (
<Box movieName = {aa} />
);})
我认为最好从组件中分离出来。
这是一种方式:
// assuming the DB is something like this based on your .map example
const MovieDatabase = [
{ title: 'Star Wars: II', id: 0 },
{ title: 'Star Wars: I', id: 1 },
{ title: 'Star Wars: IV', id: 2 },
{ title: 'Moon', id: 3 }
]
// array of star wars movies
const starWars = MovieDatabase.filter(movie => movie.title.includes('Star Wars'))
// component to render movies ( doesn't care about anything but rendering )
const MovieBoxes = movies => movies.map(movie => (
<Box key={movie.id} movieName={movie.title} />
)
您可以通过将过滤器包装在一个带有关键字的函数中并将其传递给包含以便您可以找到任何电影来进一步改进它。
你可以使用array.filter()
const array = [{
title: 'Star Wars',
duration: 107
}, {
title: 'Star Wars',
duration: 103
}, {
title: 'Lord Of The Rings',
duration: 500
}]
const filterArray = array.filter(film => film.title === 'Star Wars')
console.log(filterArray)
你也可以在你的null
中返回map()
作为你的过滤器,而不需要明确地使用Array#filter()
,因为React不会渲染
const showMovies = MovieDatabase.map((movie) =>{
const {title} = movie
return title.contains("Star Wars") ? <Box movieName = {title} /> : null;
})