如何将输入从React Form传递到Axios获取请求并显示请求结果?

时间:2019-11-08 11:38:55

标签: javascript node.js reactjs axios yelp-fusion-api

我正在尝试从用户那里获取输入,并将该输入传递到axios get中,完成后,结果信息将传递到一个数组中,该数组将显示为卡。

我遇到了以下代码正在编译的问题,但是当在表单字段中输入值并按Submit时,什么也没发生。 Web控制台中也没有任何显示。

我哪里出错了?

const initial_state = {
  location: "",
  cuisine: "",
  searchResults: []
};


class SearchMealForm extends Component {
  constructor(props) {
    super(props);
    this.state = { ...initial_state };
  }
  //handle user input and inject it into yelp api get request
  handleSubmit = event => {
    event.preventDefault();
    const { location, cuisine, searchResults} = this.state;
    this.props.onFormSubmit(this.state(location, cuisine, searchResults));
    axios.get(`https://api.yelp.com/v3/businesses/search?location=${location}+IE&categories=${cuisine}`)
    .then(response => this.setState({searchResults}))
  };

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  //YELP http api get request
  searchYelpRestaurants = (location, cuisine, searchResults) => {
    axios
      .get(
        `https://api.yelp.com/v3/businesses/search?location=${location}+IE&categories=${cuisine}`,
        {
          headers: {
            Authorization: `Bearer ${process.env.REACT_APP_API_KEY_YELP}`
          }
        }
      )
      .then(res => this.setState({ searchResults: res.data.businesses }));
  };

  render() {
    const { location, cuisine } = this.state;

    //create cards with the results from the Yelp API GET
    const YelpSearchResults = this.state.searchResults.map(result => {
      return (
        <div className="ResultCard">
          <Card style={{ width: "18rem" }}>
            <Card.Img variant="top" src={result.image_url} />
            <Card.Body>
              <Card.Title>{result.name}</Card.Title>
            </Card.Body>
            <ListGroup className="list-group-flush">
              <ListGroupItem>{result.categories}</ListGroupItem>
              <ListGroupItem>{result.rating}</ListGroupItem>
            </ListGroup>
            <Button variant="primary">Book restaurant</Button>
          </Card>
        </div>
      );
    });
    // return YelpSearchResults;
    // }

    return (
      <React.Fragment>
        <div className="SearchMeal">
          <Form onSubmit={this.handleSubmit}>
            <Form.Row>
              <Form.Group as={Col}>
                <Form.Label>City</Form.Label>
                <Form.Control
                  name="location"
                  type="text"
                  value={location}
                  onChange={this.handleChange}
                  placeholder="location"
                />
              </Form.Group>
            </Form.Row>
            <Form.Row>
              <Form.Group as={Col}>
                <Form.Label>Cuisine</Form.Label>
                <Form.Control
                  name="cuisine"
                  type="text"
                  value={cuisine}
                  onChange={this.handleChange}
                  placeholder="cuisine"
                />
              </Form.Group>
            </Form.Row>
            <Button>Submit</Button>
            <Button>Clear</Button>
          </Form>
        </div>

        {YelpSearchResults}
      </React.Fragment>
    );
  }
}

export default SearchMealForm;

2 个答案:

答案 0 :(得分:1)

此处应将按钮类型指定为提交

        <Button type="submit">Submit</Button>

为了使表单提交工作!

答案 1 :(得分:0)

我会重构您的组件以使其正常运行

import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import {
  Col,
  Form,
  Card,
  Button,
  ListGroup,
  ListGroupItem
} from "react-bootstrap";

const initial_state = {
  location: "",
  cuisine: "",
  searchResults: []
};

const SearchMealForm = ({ onFormSubmit = () => {} }) => {
  const [state, setState] = useState(initial_state);
  //handle user input and inject it into yelp api get request
  const handleSubmit = async event => {
    event.preventDefault();
    const { location, cuisine } = state;
    onFormSubmit(state);
    const searchResults = await searchYelpRestaurants({ location, cuisine });
    setState({ ...state, searchResults });
  };

  const handleChange = event => {
    setState({
      ...state,
      [event.target.name]: event.target.value
    });
  };

  //YELP http api get request
  const searchYelpRestaurants = async ({ location, cuisine }) => {
    try {
      const { data: { businesses: searchResults } = {} } = await axios.get(
        `https://api.yelp.com/v3/businesses/search?location=${location}+IE&categories=${cuisine}`,
        {
          headers: {
            Authorization: `Bearer dBMqyRFmBBg7DMZPK9v3rbGHmrLtlURpNUCJP6gbYHtyHTmboF-Mka-ZkHiDNq-G9ktATohJGD5iKQvelOHg3sDorBDiMgnsaa8SzTH8w6hjGQXlaIexDxFlTW3FXXYx`
          }
        }
      );
      return searchResults;
    } catch (err) {
      console.error(err);
    }
    return [];
  };

  const { location, cuisine, searchResults } = state;

  //create cards with the results from the Yelp API GET
  const YelpSearchResults = searchResults.map(result => (
    <div className="ResultCard">
      <Card style={{ width: "18rem" }}>
        <Card.Img variant="top" src={result.image_url} />
        <Card.Body>
          <Card.Title>{result.name}</Card.Title>
        </Card.Body>
        <ListGroup className="list-group-flush">
          <ListGroupItem>{result.categories}</ListGroupItem>
          <ListGroupItem>{result.rating}</ListGroupItem>
        </ListGroup>
        <Button variant="primary">Book restaurant</Button>
      </Card>
    </div>
  ));

  return (
    <React.Fragment>
      <div className="SearchMeal">
        <Form onSubmit={handleSubmit}>
          <Form.Row>
            <Form.Group as={Col}>
              <Form.Label>City</Form.Label>
              <Form.Control
                name="location"
                type="text"
                value={location}
                onChange={handleChange}
                placeholder="location"
              />
            </Form.Group>
          </Form.Row>
          <Form.Row>
            <Form.Group as={Col}>
              <Form.Label>Cuisine</Form.Label>
              <Form.Control
                name="cuisine"
                type="text"
                value={cuisine}
                onChange={handleChange}
                placeholder="cuisine"
              />
            </Form.Group>
          </Form.Row>
          <Button type="submit">Submit</Button>
          <Button>Clear</Button>
        </Form>
      </div>

      {YelpSearchResults}
    </React.Fragment>
  );
};

export default SearchMealForm;
<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>