gpt4 book ai didi

javascript - react : How do I move my ajax api call into a separate component?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:42:27 24 4
gpt4 key购买 nike

这是一个运行良好的典型容器组件:

const API = 'https://randomuser.me/api/?results=5';
class App extends Component {

constructor(props) {
super(props);
this.state = { profiles: [] };
}

componentDidMount() {
this.fetchProfiles();
}

fetchProfiles() {
let url = API;
fetch(url)
.then( (res) => res.json() )
.then( (data) => {
let results = data.results;
this.setState({
profiles: results
});
})
.catch( (error) => console.log('Oops! . There Is A Problem', error) );
}

render() {
// rendering child component here
}
}

export default App;

我现在要做的是将 fetchProfiles 函数移动到一个单独的 api 组件中。

所以我在项目的 api 文件夹中创建了一个 profiles.js 文件:

const API = 'https://randomuser.me/api/?results=5';

export function fetchProfiles() {
let url = API;
fetch(url)
.then( (res) => res.json() );
}

现在我的主要组件导入它并像这样使用它:

import { fetchProfiles } from '../api/profiles.js';


const API = 'https://randomuser.me/api/?results=5';
class App extends Component {

constructor(props) {
super(props);
this.state = { profiles: [] };
}

componentDidMount() {
fetchProfiles.then((data) => {
let results = data.results;
this.setState({
profiles: results
});
});
}

// render call etc

但是当我像这样在 componentDidMount 中运行调用时,我收到此错误:Uncaught TypeError: _profiles.fetchProfiles.then is not a function。我正在尝试与 then 链接,因为 fetch api 返回 res.json() 作为 promise 。

我尝试将 fetchProfiles 包装在一个外部函数中,也在一个新的 promise 中!但是没有任何效果!我在这里做错了什么?请帮助进行此重构。

最佳答案

你需要返回 fetch(url) 本身,所以你会返回一个 promise ,然后你可以使用 then 方法:

const API = 'https://randomuser.me/api/?results=5';

export function fetchProfiles() {
let url = API;

// return the promise itself
return fetch(url).then( (res) => res.json() );
}

关于javascript - react : How do I move my ajax api call into a separate component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509813/

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