我正在尝试使用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获取数据?我一次又一次尝试,但失败了。
答案 0 :(得分:0)
只需将baseUrl
更改为baseURL
即可使用。
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
dictionary.js
import axios from 'axios';
export default axios.create({
baseURL: `https://googledictionaryapi.eu-gb.mybluemix.net`,
});
,并且searchbar.js
中没有任何更改。我对index.js进行了一些更改,并将在输入的onChange上发送请求。