用React搜索YouTube
我有一个简单的应用程序来搜索YouTube。当我运行它时,我没有得到任何错误,但是当我点击搜索按钮时没有发生任何事情!用React搜索YouTube
下面是相关代码:
class App extends React.Component{ constructor() {
super();
this.state = {
searchResults: []
}
this.search = this.search.bind(this);
this.showResults = this.showResults.bind(this);
}
showResults(response) {
this.setState({
searchResults: response.results
})
console.log(response)
}
search(searchTerm) {
fetch("www.googleapis.com/youtube/v3/search", {
type: "GET",
part: 'snippet',
url: "www.googleapis.com/youtube/v3/search",
key: "AIzaSyCBPX-gonEMREh2OyT3S9Q7oaxBFaxkBZs",
q: searchTerm,
success: function(response) {
this.showResults(response);
}.bind(this)
});
}
render() {
return (
<div>
<Searchbox search={this.search}/>
<Mapresults searchResults={this.state.searchResults} />
</div>
)
}
}
class Searchbox extends React.Component{
createAjax(){
var url = 'https://www.googleapis.com/youtube/v3/search';
var key = 'AIzaSyCBPX-gonEMREh2OyT3S9Q7oaxBFaxkBZs';
var searchresult = ReactDOM.findDOMNode(this.refs.query).value;
var fullUrl = url + key + searchresult;
this.props.search(fullUrl);
}
render(){
return(
<div>
<form id="search-term">
<input ref="query" type="text"/><button id="search-term" onChange=
{() => this.createAjax.bind(this)}/>
</form>
<h2 id= "root">test</h2>
<h2 id="demo"></h2>
</div>
)
}
}
我试图修复它,并加入反应开发工具,但它似乎只是不渲染。
回答:
而不是使用检索您的ReactDOM.findDOMNode(this.refs.query).value
搜索框的值,请尝试使用controlled component模式。这允许组件的状态驱动演示文稿,而不是相反。
这是你的搜索框组件的一个片段,与实施控制组件模式:
class Searchbox extends React.Component { constructor() {
super();
this.state = {
searchText: ''
};
}
handleSearchClick = e => {
var url = "https://www.googleapis.com/youtube/v3/search";
var key = "AIzaSyCBPX-gonEMREh2OyT3S9Q7oaxBFaxkBZs";
var searchresult = this.state.searchText;
var fullUrl = url + key + searchresult;
this.props.search(fullUrl);
};
handleInputChange = e => {
this.setState({ searchText: e.target.value });
};
render() {
return (
<div>
<form id="search-term">
<input
ref="query"
type="text"
value={this.state.searchText}
onChange={this.handleInputChange}
/>
<button
id="search-term"
type="button"
onClick={this.handleSearchClick}
>
Search
</button>
</form>
<h2 id="root">test</h2>
<h2 id="demo" />
</div>
);
}
}
使这一变化让我成功地调用的YouTube API,虽然我收到了'Access-Control-Allow-Origin'
错误,我假设你将在你的实际代码中处理。
以上是 用React搜索YouTube 的全部内容, 来源链接: utcz.com/qa/261518.html