【问题标题】:Unhandled Promise Rejection: Syntax Error未处理的承诺拒绝:语法错误
【发布时间】: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*/}

标签: reactjs api onclick fetch


【解决方案1】:

您需要.catch() 来处理 Promise 拒绝。本质上,它只是在您的 API 请求失败时执行的后备逻辑。

此外,您的 API 请求看起来不正确。您不必将 state 对象放在路径中。我假设你真正想要的是从你的饮料数组中添加一个字符串。

componentDidMount() {
    const requestOptions = {
        method: 'GET', 
    }

    fetch(INGREDIENT_SEARCH_API_URL + "/" + this.state.drinks[0], 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 });
        })
        .catch((errors) => {
            console.log(errors)
        })
}

【讨论】:

  • 是的;我想添加表单中提交的任何饮料
  • 正确,因此您不希望将对象 {} 传递给 URL 路径。你知道 API 在反斜杠之后是否真的想要一个对象?似乎他们想要一个字符串@JasonCalk
【解决方案2】:

你为什么要在 this.state 后面加上 Api 端点 url。 fetch 的第一个参数是端点 url,它必须是一个字符串。获取(网址,{选项})。 如果您想在 url 上传递查询,请使用 '?'

    const data=["aa","bb","cc"]
    const stringData=data.join()
    const params='?'+stringdata
    fetch(INGREDIENT_SEARCH_API_URL+params, requestOptions)
                .then(responseData => {
                    this.setState({ drinks: responseData });
                })
                .catch(res => {
                    if (!res.ok) {
                        console.log('Blame it on the rain');
                    }
                })

【讨论】:

    【解决方案3】:

    所以,我终于想通了。感谢您一路上的帮助。

    export default class App extends Component {
      constructor(props) {
        super(props);
    
        this.textInput = React.createRef();
        this.searchValue = '';
    
        this.state = {
          drinks: []
        }
      }
    
      handleChange = () => {
        console.log('change', this.searchValue);
        this.searchValue = this.textInput.current.value;
      }
    
      handleSearchClick = () => {
        const requestOptions = {
          method: "GET"
        };
    
        fetch(INGREDIENT_SEARCH_API_URL + this.searchValue, requestOptions)
          .then(res => {
            if (!res.ok) {
              console.log('error');
            }
            return res.json();
          })
          .then(response => {
            console.log(response.drinks);
            this.setState({ drinks: response.drinks });
            this.props.history.push('/');
          })
          .catch(err => {
            console.log(err);
            this.props.history.push('/');
          })
      }
    
      gotoDrink = (id) => {
        this.props.history.push('/d/' + id)
      }
    
      render() {
        return (
          <div className="App">
            <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" ref={this.textInput} onChange={() => this.handleChange()} />
                  <Button variant="outline-success" onClick={() => this.handleSearchClick()}>Search</Button>
                </Form>
              </Navbar.Collapse>
            </Navbar>
            <div className="Content">
              <Route
                path="/" exact
                render={() => (
                  <div className="LeftContent">
                    {this.state.drinks.map(drink => (
                      <div className="DrinkName" onClick={() => this.gotoDrink(drink.idDrink)}>
                        {drink.strDrink}
                      </div>
                    ))}
                  </div>
                )}
              />
              <Route
                path="/d/:id"
                render={(props) => <DrinkComponent {...props} />}
              />
            </div>
          </div>
        )
      }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      相关资源
      最近更新 更多