は完璧にうまく機能している典型的なコンテナコンポーネントです:React:ajax APIコールを別のコンポーネントに移動するにはどうすればよいですか?ここ
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;
私が今やろうとしていますどのような別のAPIコンポーネントにfetchProfiles
機能を移動しています。
だから私は私のプロジェクトで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()
を返します。
外部機能にfetchProfiles
をラッピングしてみましたが、これも新しい約束です!しかし、何も動作しません!私はここで間違って何をしていますか?このリファクタリングを手伝ってください。
const API = 'https://randomuser.me/api/?results=5';
export function fetchProfiles() {
let url = API;
return fetch(url)
.then((response) => response.json());
}
そして、コンテナコンポーネントに:私はこれを固定方法はfetch(url)
自体を返すようにした
あなたは(URL)をフェッチ '返す必要がし'自体は、あなたが戻りますので、約束してから、 'then'メソッドを使うことができます。 –