onSubmit is not executing async function

问题: I'm trying to submit a function that will generate a gif, when pressing the get gif button. However, it does not show anything in the console, and the page reloads. 1)...

问题:

I'm trying to submit a function that will generate a gif, when pressing the get gif button.

However, it does not show anything in the console, and the page reloads.

1) I want the client to type in a value

2) set the value to the like so

ex.

http://api.giphy.com/v1/gifs/search?q=USER_VALUE&api_key=iBXhsCDYcnktw8n3WSJvIUQCXRqVv8AP&limit=5

3) fetch the value and return like the following

enter image description here

Current project

https://stackblitz.com/edit/react-4mzteg?file=index.js

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Card from './Card';
import { throws } from 'assert';

class App extends Component {

  constructor(props){
    super(props);

    this.state = {
      query: '',
      slug:undefined,
      url:undefined
    }

    this.onChange = this.onChange.bind(this);

  }

  onChange(e){
    this.setState({
      query: e.target.query
    })
  }



  getGIY = async (e) =>{

    try {
      const {slug, url} = this.state;
      const query = this.state._query 
      const response = await fetch(`http://api.giphy.com/v1/gifs/search?q=${query}&api_key=iBXhsCDYcnktw8n3WSJvIUQCXRqVv8AP&limit=5`);
      const data = await response.json();
      const mainData = data.data;
      if(query){
        this.setState({
          slug: mainData[0].title,
          url: mainData[0].images.downsized.url
        });

        console.log(mainData);
      }

    } catch (error) {
      console.log(error);
    }



  }


  render() {
    return(
      <div>
        <h1> Welcome</h1>

        <form onSubmit={this.props.getGIY}>
                        <input type="text" name="query" onChange={this.onChange} ref={(input) => {this.state._query = input}} placeholder="Search GIF..."/>
                        <button>Get GIF</button>

                </form>

        <Card slug={this.state.slug} url={this.state.url}/>
      </div>
    );

  }

}

export default App;

Card.js

import React, {Component} from 'react';

const Styles = {
    width: '300px',
    height: '300px'
}

class Card extends React.Component {

    render() {

        return (

            <div>
                <h1>{this.props.slug}</h1>

                <div>
                    <img src={this.props.url}/>
                </div>

            </div>

        );

    }

}

export default Card;

回答1:

You are missing 2 3 4 things

1) instead of this.props.getGIY you need to use this.getGIY

2) as you are using form you need to preventdefault using

getGIY = async (e) =>{
   e.preventDefault();

3) instead of e.target.query you need to get e.target.value

4) instead of const query = this.state._query you need to use const query = this.state.query your state name is query

  onChange(e){

    this.setState({
      query: e.target.value
    })
  }

Demo

Your getGIY function

  getGIY = async (e) =>{
   e.preventDefault();      
    try {
      const {slug, url} = this.state;
      const query = this.state._query 
      const response = await fetch(`http://api.giphy.com/v1/gifs/search?q=${query}&api_key=iBXhsCDYcnktw8n3WSJvIUQCXRqVv8AP&limit=5`);
      const data = await response.json();
      const mainData = data.data;
      if(query){
        this.setState({
          slug: mainData[0].title,
          url: mainData[0].images.downsized.url
        });

        console.log(mainData);
      }

    } catch (error) {
      console.log(error);
    }



  }

Your form

  <form onSubmit={this.getGIY}>
    <input type="text" name="query" onChange={this.onChange} ref={(input) => {this.state._query = input}} placeholder="Search GIF..."/>
                        <button>Get GIF</button>

  </form>

回答2:

Mixing promises and try/catch blocks is a little messy as promises themselves duplicate much of the behavior of try/catch blocks. Promises are also chainable. I suggest this edit for your getGIY function. It's just as readable as the existing try/catch w/ unchained promises but more idiomatic (e.g. if THIS is successful, THEN do this next), and more importantly it's a bit more succinct.

getGIY = async (e) =>{
  e.preventDefault();
  const { query } = this.state;

  /* fetch and response.json return promises */

  await fetch(`http://api.giphy.com/v1/gifs/search?q=${query}&api_key=iBXhsCDYcnktw8n3WSJvIUQCXRqVv8AP&limit=5`)

  // fetch resolved with valid response
  .then(response => response.json())

  // response.json() resolved with valid JSON data
  // ({ data }) is object destructuring (i.e. data.data)
  .then(({ data }) => {
    this.setState({
      slug: data[0].title,
      url: data[0].images.downsized.url
    });
  })

  /* use catch block to catch any errors or rejected promises */
  .catch(console.log); // any errors sent to log
}
  • 发表于 2018-12-28 16:59
  • 阅读 ( 231 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除