onSubmit没有执行异步功能

时间:2018-12-27 04:05:05

标签: javascript reactjs

我试图提交一个函数,当按下获取gif按钮时,该函数将生成gif。

但是,它在控制台中不显示任何内容,并且页面会重新加载。

1)我希望客户端输入一个值

2)将值设置为类似

例如。

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

3)获取值并返回如下内容

enter image description here

当前项目

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;

2 个答案:

答案 0 :(得分:3)

您缺少了 2 3 4件事

1)而不是this.props.getGIY,您需要使用this.getGIY

2)在使用表单时,您需要使用

防止默认设置
getGIY = async (e) =>{
   e.preventDefault();

3)您需要获取e.target.value而不是e.target.query

4)您需要使用const query = this.state._query而不是const query = this.state.query,您的州名是查询

  onChange(e){

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

Demo

您的getGIY函数

  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);
    }



  }

您的表格

  <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>

答案 1 :(得分:0)

混合promise和try / catch块有点混乱,因为promise自身会复制try / catch块的许多行为。承诺也是可链接的。我建议您对getGIY函数进行此编辑。它与现有的try / catch w / unchained promises一样可读,但是更加惯用(例如,如果此操作成功,则接下来执行此操作),更重要的是,它更加简洁。

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
}