【发布时间】:2019-08-06 17:21:17
【问题描述】:
我正在尝试调用 api 并取回数据;由我的表单定义并将 onclick 附加到我的 api。我只做了很短的时间,所以任何帮助将不胜感激。我的主要问题(我认为)是如何正确添加到 api 调用,如何将我的表单从表单获取到 api 请求,以及如何让它重新填充我的状态。我看过其他几个类似的帖子,但它们只是让我更加困惑,因为他们使用不同的调用方法和 api 或其他东西,这让我比开始时有更多的问题。任何帮助,将不胜感激。
import React, { Component } from 'react';
import { Navbar, Form, FormControl, Button } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCocktail } from '@fortawesome/free-solid-svg-icons';
import { INGREDIENT_SEARCH_API_URL } from '../../config';
class Nav extends Component{
constructor(props) {
super(props);
this.state = {
drinks: [], //is this the right field from the api?
};
}
componentDidMount() {
const requestOptions = {
method: 'GET',
}
fetch(INGREDIENT_SEARCH_API_URL + this.state, requestOptions)
// what gets appended to the api?
.then(res => {
if (!res.ok) {
console.log('Blame it on the rain');
}
return res.json();
})
.then(responseData => {
this.setState({ drinks: responseData });
})
}
render() {
return (
<div className="Nav">
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">
<FontAwesomeIcon icon={faCocktail} /> Mix It Up!
</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Form inline>
<FormControl type="text" placeholder="Search" className="mr-sm-2" />
<Button type="submit" onClick={() => this.getdrinks()} variant="outline-success">Search</Button>
{/* What goes into the onClick function? */}
</Form>
</Navbar.Collapse>
</Navbar>
<div className="NavContent">
{this.state.drinks.map(drink => ( drink ))}
</div>
</div>
)
}
}
export default Nav
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
【问题讨论】:
-
为什么要在 URL 后面加上
this.state? -
idk...我使用的示例... this.props.match.params.{/*component*/}