gpt4 book ai didi

javascript - Axios 在 React 组件中返回未定义

转载 作者:行者123 更新时间:2023-12-03 02:15:05 25 4
gpt4 key购买 nike

本质上我有一个输入字段和一个提交按钮。我的目标是让输入字段成为 axios 请求中所请求的内容。

这是我的 axios 请求的代码:

import axios from 'axios';

module.exports = {
getItunesArtists: function(ARTIST_NAME) {
var encodedURI = window.encodeURI('https://itunes.apple.com/search?term=' + ARTIST_NAME);

return axios.get(encodedURI).then(function(response) {
console.log('response.data.items', response.data.items);
});
},
};

控制台返回

response.data.items 未定义

这是我的主要组件和功能组件。

import React, { Component } from 'react';
import api from '../utils/api';

import axios from 'axios';

// prettier-ignore
function Albums(props) {
return (
<ul>
{props.albums.map(function(album, index) {
return (
<li key={album.name} >

<ul >
<li>
{console.log(album)}
</li>

</ul>
</li>
);
})}
</ul>
);
}

export default class App extends Component {
constructor(props) {
super(props);
this.state = { albums: [], artistSearched: '', dirty: false };
this.handleSearchTermChange = this.handleSearchTermChange.bind(this);
this.getAlbums = this.getAlbums.bind(this);
}

componentDidMount() {
this.getAlbums(this.state.artistSearched);
}

getAlbums(artist) {
this.setState(function() {
return {
artistSearched: artist,
albums: [],
};
});
api.getItunesArtists(artist).then(
function(artists) {
this.setState(function() {
return {
albums: artists,
};
});
}.bind(this)
);
}

handleSearchTermChange(event) {
console.log(event.target.value);
this.setState({ artistSearched: event.target.value });
}

render() {
const { albums, artistSearched } = this.state;

return (
<div>
<h1>Itunes Album Fetcher</h1>
<form style={{ marginTop: '20px' }}>
<input
onChange={this.handleSearchTermChange}
value={this.state.artistSearched}
className="form-control"
placeholder="Enter album name"
/>
<button type="submit" disabled={!artistSearched}>
Search
</button>
</form>
{!this.state.albums ? <p>Loading</p> : <Albums albums={this.state.albums} />}
</div>
);
}
}

提前谢谢您!

最佳答案

您是 console.logging response.data.items,但是当我调用此 API 时,我看到响应的格式不同:

{
"resultCount":50,
"results": [ ... ]
}

您想要使用response.data.results

关于javascript - Axios 在 React 组件中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49395229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com