将数组传递给组件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数组传递给组件相关的知识,希望对你有一定的参考价值。
我遇到了一个问题,我试图将一个从DB中获取的数组从一个组件发送到另一个组件,我的意思是,我正在获取JSON数据,然后这些数据必须被传递到另一个组件中。
import React from 'react'
import { withRouter } from 'react-router-dom'
import MovieList from './MovieList'
import MoviesService from '../services/MoviesService'
class MovieListGet extends React.Component {
constructor (props) {
super(props)
this.state = {
movies: []
}
}
async componentDidMount () {
await this._getMovies()
}
async _getMovies () {
const response = await MoviesService.getMovies()
this.setState({ movies: response.data })
console.log(this.state.movies)
}
async _deleteMovie (id) {
}
_navigateToCreateMovies () {
// Adrress
}
render () {
return (
<div>
<MovieList
movies = {this.state.movies}
onCreateMovie={this._navigateToCreateMovies.bind(this)}
onDelete={this._deleteMovie.bind(this)}
/>
</div>
)
}
}
export default withRouter(MovieListGet)
获取数组的类
/* eslint-disable react/prop-types */
import React from 'react'
import {...} from '@material-ui/core'
import { ... } from '@material-ui/icons'
class MovieList extends React.Component {
constructor (props) {
super(props)
const { movies } = props
this.state = {
_movies: []
}
}
componentDidMount () {
console.log(this.props.movie)
this.setState({ _movies: this.props.movies })
}
_renderMovies () {
if (!this.state._movies || this.state._movies.length < 1) {
return (
// Something
)
} else {
return this.state._movies.map(m => (
// something
)
)
}
}
render () {
return (
// Something
)
}
}
export default (MovieList)
答案
MoviesListGet应该像这样传递道具。
<MovieList
movies={this.state.movies}
onCreateMovie={this._navigateToCreateMovies.bind(this)}
onDelete={this._deleteMovie.bind(this)}
/>
然后在MoviesList组件中,你可以像这样在renderMovies方法中使用它。
class MovieList extends React.Component {
renderMovies () {
if (!this.props.movies || this.props.movies.length < 1) {
return (
// Something
)
} else {
return this.props.movies.map(m => (
// something
)
)
}
}
render () {
return (
// Something
)
}
}
export default MovieList;
以上是关于将数组传递给组件的主要内容,如果未能解决你的问题,请参考以下文章