为什么渲染功能不起作用?
why isn't the render function working?
我正在尝试制作一个从 Youtube Api 获取数据的 React 应用程序。 App 是我的主要组件,VideoList 是一个子组件。当我将 VideoList 组件包含到 App 组件的渲染函数中时,控制台显示错误并且输出为空白 page.according 对我来说输出应该是 5,因为视频数组的长度是 5。我不明白在哪里我正在 mistake.i 新手做出反应,如有任何帮助,我们将不胜感激。这是我的代码
应用组件
class App extends Component {
constructor(props)
{
super(props);
this.state={ videos: [] };
YTSearch({key:API_KEY, term:'surfboards'},(data) =>{
this.setState({videos:data});
} );
}
render()
{
return (
<div>
<SearchBar/>
<VideoList videos={this.state.videos}/>
</div>
);
}
}
VideoList 组件
const VideoList = (props) =>
{
return
( <div>
<ul className="col-md-4 list-group">
{props.videos.length}
</ul>
</div>
);
}
我觉得,你写组件的方式有问题,你需要这样写:
const VideoList = (props) => {
return ( // ( should be in the same line
<div>
<ul className="col-md-4 list-group">
{props.videos.length}
</ul>
</div>
);
}
因为如果你这样写:
return
(
.....
它不会 return
任何东西,将被视为 return;
建议: 不要在 constructor
中获取数据,而是在 componentDidMount
生命周期中调用 api,如下所示:
componentDidMount(){
YTSearch({key:API_KEY, term:'surfboards'},
(data) => {
this.setState({videos:data});
}
)
}
我正在尝试制作一个从 Youtube Api 获取数据的 React 应用程序。 App 是我的主要组件,VideoList 是一个子组件。当我将 VideoList 组件包含到 App 组件的渲染函数中时,控制台显示错误并且输出为空白 page.according 对我来说输出应该是 5,因为视频数组的长度是 5。我不明白在哪里我正在 mistake.i 新手做出反应,如有任何帮助,我们将不胜感激。这是我的代码
应用组件
class App extends Component {
constructor(props)
{
super(props);
this.state={ videos: [] };
YTSearch({key:API_KEY, term:'surfboards'},(data) =>{
this.setState({videos:data});
} );
}
render()
{
return (
<div>
<SearchBar/>
<VideoList videos={this.state.videos}/>
</div>
);
}
}
VideoList 组件
const VideoList = (props) =>
{
return
( <div>
<ul className="col-md-4 list-group">
{props.videos.length}
</ul>
</div>
);
}
我觉得,你写组件的方式有问题,你需要这样写:
const VideoList = (props) => {
return ( // ( should be in the same line
<div>
<ul className="col-md-4 list-group">
{props.videos.length}
</ul>
</div>
);
}
因为如果你这样写:
return
(
.....
它不会 return
任何东西,将被视为 return;
建议: 不要在 constructor
中获取数据,而是在 componentDidMount
生命周期中调用 api,如下所示:
componentDidMount(){
YTSearch({key:API_KEY, term:'surfboards'},
(data) => {
this.setState({videos:data});
}
)
}