因此,通过使用邮递员,我设法为yummly调用网址。我想渲染我的搜索结果。目前在第29-36行的渲染中,我有一个假搜索只是为了确保Dom工作,它确实如此。如何从第52-60行获取api搜索以在29-36中显示。
import React from 'react';
import Request from 'superagent';
import _ from 'lodash';
export class Yum extends React.Component {
constructor(){
super();
this.state = {};
}
componentWillMount(){
/*var url = "http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&=q"
Request.get(url).then((response) => {
console.log(response.body);
this.setState({
recipes: response.body.matches,
total: response.body.totalResults
});
});*/
this.search();
}
updateSearch(){
this.search(this.refs.query.value);
}
render(){
const title = 'Onion Soup';
const ingredients = ["onions", "beef stock"];
const listItems = ingredients.map((ingredient) => {
return (<h5>{ingredient}</h5>);
});
return(
<div>
<input ref="query" onChange = { (e) => {this.updateSearch();} } type="text" />
<h4>{title}</h4>
<ul>
<li>{listItems}</li>
</ul>
</div>
)
}
search(query = "onion") {
var url = `http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&=q${query}&maxResult=1`
Request.get(url).then((response) => {
console.log(response.body.matches[0]);
console.log(query);
this.setState({
recipes: response.body.matches[0],
//total: response.body.totalResults
});
});
}
}
export default Yum;
答案 0 :(得分:0)
Here you go I have cleaned up your code a bit, please give it a try
import React from 'react';
import Request from 'superagent';
import _ from 'lodash';
export class Yum extends React.Component {
constructor(){
super();
this.state = {
searchQuery: 'onion'
recipe: {
ingredients: []
}
};
this.search = this.search.bind(this);
this.queryUpdate = this.queryUpdate.bind(this);
}
componentWillMount(){
this.search(this.state.searchQuery);
}
render(){
const title = 'Onion Soup'; // Get this from somwhere else ?
const {recipe, searchQuery} = this.state; // Get state properties
const listItems = _.get(recipe, 'ingredients', []).map((ingredient) => {
return (<h5>{ingredient}</h5>);
});
return(
<div>
<input onChange={this.queryUpdate} type="text" value={searchQuery} />
<h4>{title}</h4>
<ul>
<li>{listItems}</li>
</ul>
</div>
)
}
queryUpdate(e) {
const searchQuery = event.target.value; // Get new value from DOM event
this.setState({searchQuery}); // Save to state
this.search(searchQuery); // Search
}
search(searchQuery) {
const url = `http://api.yummly.com/v1/api/recipes?_app_id=5129dd16&_app_key=9772f1db10ba433223ad4e765dc2b537&q=${searchQuery}&maxResult=1`
Request.get(url).then((response) => {
this.setState({
recipe: response.body.matches[0]
});
});
}
}
export default Yum;
Here are some of the issues I noticed: