繁体   English   中英

如何获取 API?

[英]How can I fetch API?

我正在尝试使用 axios 在 React 中获取 API。 所有代码在这里,/*********************************************** */

Index.js 组件

import React, { Component } from 'react';
import { render } from 'react-dom';
import SearchBar from './SearchBar/searchbar';
import './style.css';
import dictionary from './API/dictionary';

class App extends Component {
  constructor() {
    super();
    this.state = {
      word:''
    };
  }

  changeHandler = (e) => {
    this.setState({word: e.target.value})
  }
  onSearchSubmit = async (e) => {
     const response = await dictionary.get(`/?define=${this.state.word}`)
  console.log(response);
    this.setState({word:this.state.word});
  };


  render() {
    return (
      <div className='ui container'>
        <SearchBar 
          change={this.changeHandler}
          onSubmitted={this.onSearchSubmit}
          value={this.state.word}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

下面是搜索栏组件:

import React from 'react';
const SearchBar = (props)=> {
  return (
    <div className='search-bar ui segment'>
      <form onSubmit={props.onSubmitted} className='ui form'>
        <div className='field '>
          <label>Search Bar </label>
          <input type='text'
                placeholder='Type any word to know the meaning' 
                onChange={props.change}
                value={props.value}
                /> 
        </div>
      </form>
    </div>
  )
}
export default SearchBar;

** 以下是 Axios 实例:**

import axios from 'axios';
export default axios.create({
  baseUrl: 'https://googledictionaryapi.eu-gb.mybluemix.net'
});

什么是正确的代码? 可以从这个api获取数据吗? 我一次又一次地尝试但失败了。

只是改变baseUrlbaseURL ,并将努力。

index.js 组件

import React, { Component } from 'react';
import { render } from 'react-dom';
import SearchBar from './SearchBar/searchbar';
import './style.css';
import dictionary from './API/dictionary';

class App extends Component {
  constructor() {
    super();
    this.state = {
      word:''
    };
  }

  changeHandler = (e) => {
    this.setState({word: e.target.value}, ()=> this.onSearchSubmit())
  }
  onSearchSubmit = async (e) => {
     const response = await dictionary.get(`/?define=${this.state.word}`)
  console.log(response);
    this.setState({word:this.state.word});
  };


  render() {
    return (
      <div className='ui container'>
        <SearchBar 
          change={this.changeHandler}
          onSubmitted={this.onSearchSubmit}
          value={this.state.word}
        />
      </div>
    );
  }
}
export default App

字典.js

import axios from 'axios';
export default axios.create({
    baseURL: `https://googledictionaryapi.eu-gb.mybluemix.net`,
});

并且searchbar.js没有变化。 我稍微改变了 index.js 并将发送请求 onChange 输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM