![](/img/trans.png)
[英]In React js from App.js how to call another javascript file (service) method to consume API calls
[英]tried to move my api calls from App.js to actions file
https://codesandbox.io/s/redux-async-actions-b5d0t
axios
.get("https://reqres.in/api/users?page=2")
// axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
// console.log("response.data.data---->", response.data.data);
// console.log(
// "response.data.data[0].id---->",
// response.data.data[0].id
// );
//First of all we'll create the number of requestes base on the previous Response
const promises = response.data.data.reduce(
(previousValue, { id }) => {
previousValue.push(
axios.get(
`https://jsonplaceholder.typicode.com/comments?postId=${id}`
)
);
// console.log(
// " promises previousValue---->",
// previousValue
// );
return previousValue;
},
[]
);
// console.log("promises---->", promises);
//We use the built in function to fetch the data
axios.all(promises).then(responses => {
//Here you have all responses processed
const emailsMapped = responses.reduce(
(previousValue, { data }) => {
const emails = data.map(({ email }) => email);
previousValue.push(...emails);
// console.log(
// "axios all previousValue---->",
// previousValue
// );
return previousValue;
},
[]
);
//You send the emails you want
this.props.onFetchSuccess(emailsMapped);
// console.log("CHECK");
// console.log(emailsMapped);
});
})
.catch(err => {
// this.props.onFetchError();
// dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err });
});
您應該將 this.props 作為參數提供給您在 actions/index.js 中調用的 function。
你應該稱之為: fetchUsers(this.props)
在 actions/index.js fetchUsers(props) { props.onFetch(); ... props.onFetchSuccess(emailsMapped); }
fetchUsers(props) { props.onFetch(); ... props.onFetchSuccess(emailsMapped); }
使用該參數而不是 this.props。
並使用const axios = require('axios');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.