我按照關於如何構建React
應用程序的教程,而且我遇到了一些奇怪的問題。React好像不會將道具傳遞給其他組件
當我嘗試將某些信息傳遞給另一個組件時,其他組件獲取props
但它是空的。
在我的情況下,index.js
是這樣的:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
const API_KEY = 'AIzaSyDdvc_zComCpdqqfmwgOsZvLOwwPEabcde';
class App extends Component {
constructor (props) {
super (props);
this.state = {
videos : []
};
}
componentDidMount() {
YTSearch (
{
key : API_KEY,
term : 'surfboards'
},
videos => {
this.setState ({ videos });
}
);
}
render() {
return (
<div>
<SearchBar />
<VideoList videos={this.state.videos} />
</div>
);
}
};
ReactDOM.render (
<App />,
document.querySelector ('.container')
);
和我的./components/video_list.js
代碼是這樣的:
import React, { Component } from 'react';
import VideoListItem from './video_list_item';
class VideoList extends Component {
constructor(props) {
super(props);
this.state = {
videoItems : []
};
}
componentDidMount() {
this.setState(
{
videoItems: this.props.videos.map(
video => {
console.log(video);
return <VideoListItem video={video} />;
}
)
}
)
}
render() {
return (
<ul className="col-md-4 list-group">{ this.state.videoItems }</ul>
);
}
}
export default VideoList;
的代碼似乎是非常strateforward,但在現實中,它有問題。
如果我嘗試在index.js
我得到以下輸出return
語句之前這一說法console.log(this.state.videos);
:
// Initially I get this because the API is not yet completed:
Array[0]
length: 0
__proto__: Array[0]
// And then, once the API Request it is completed I get this:
Array[5]
0: Object
etag : ""5C5HHOaBSHC5ZXfkrT4ZlRCi01A/2H00YaVLWV4Xof09xk9Q8k6vlxw""
id: Object
kind: "youtube#searchResult"
snippet: Object
__proto__: Object
1: Object
2: Object
3: Object
4: Object
length: 5
__proto__: Array[0]
與此同時,如果我嘗試console.log(props)
的VideoList
組件我得到的constructor
方法內以下輸出:
Object {videos: Array[0]}
videos: Array[0]
length: 0
__proto__: Array[0]
__proto__: Object
你知道什麼是錯的嗎?你看到我看不到的東西嗎?
自從您在構造函數中記錄道具後,看起來對我很正確。 React組件有一個生命週期[https://facebook.github.io/react/docs/react-component.html](https://facebook.github.io/react/docs/react-component.html)。如果您期望看到道具傳遞下來,那麼在更新生命週期中,比如'componentWillReceiveProps()' – phoa
@phoa謝謝您的回答。我要檢查'componentWillReceiveProps',我會更新你:) –
@phoa謝謝:)對我有用:) –