我在App(父)组件中将状态设置为数组。数据是可以的,当我尝试将这些数据传递给VideoList(子)组件时,它始终作为空字符串欢迎 index js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list';
import SearchBar from './components/search_bar';
const YOUTUBE_API_KEY = "AIzaSyCI9gcceui5zcQDAEwbyvL...";
class App extends Component {
constructor(props){
super(props);
this.state = {videos:''}
YTSearch({key:YOUTUBE_API_KEY, term:'surfboards'}, (videos)=>{
this.setState({videos:videos})
});
}
render(){
return (
<div>
<SearchBar />
<VideoList videos = {this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
VideoList.js
import React, {Component} from 'react';
import VideoListItem from './video_list_item';
const VideoList = (props) =>{
//I expect props as array but its empty string..
const videoItems = props.videos.map((video) => {
return <VideoListItem video={video} />
})
return (
<ul className="col-md-4 list-group">
{videoItems}
</ul>
);
}
export default VideoList;
我能够在数组中看到检索到的视频元素,所以我的问题是将其传递给子组件
答案 0 :(得分:1)
问题在于您将videos
设置为字符串:
this.state = {videos:''}
然后尝试映射:
const videoItems = props.videos.map((video) => {
return <VideoListItem video={video} />
})
这可能会引发错误(您应该能够检查控制台以查看它),并且错误可能会阻止进一步的渲染。