如何在js中有一个独立的文件来处理Reactjs中的API响应



我想把API文件从这个页面中分离出来,并想把状态发送给API,并得到主文件

的响应。我想构建我的react项目,并将我的api和方法设置在一个单独的文件中。

我有一个有API的类组件,我想添加一个新文件,并称之为submitFormAdd.js函数在这个文件中我想处理API调用和响应。

*** MAIN FILE ***

class APIForm extends React.Component {
state = {
id: '',
name: '',
description: '',
duration:'',
price: '',
}
// some function
*** want this code in different file ***
submitFormAdd = async(e) => {
fetch('http://localhost:3003/api/service', {
method: 'put',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
duration: this.state.duration,
description: this.state.description,
price: this.state.price,
})
}).then(response => response.json())

/////// wants item response here 
.then(item => {
if (item) {
// do something
}
else {
// do somthing
}
})
.catch(err => console.log(err))
}
render() {
return (
//Some JSX
);
}
}
export default APIForm

在API文件

export const AddService = async (data) => {
let d = {...data};
try{
let rs = await axios.put(URL,d)
return rs.data.data
}enter code here
catch(e){
return console.log("ERR");
}
}

和主文件

submitFormAdd = async (e) => {
e.preventDefault()
if (this.state.valid == true) {
let rs = await AddService({
name: this.state.name,
duration: this.state.duration,
description: this.state.description,
price: this.state.price,
});
this.props.addItemToState(rs)
this.props.toggle()
NotificationManager.info("Service Added Successfully", 'Info', 2000);
}
}

最新更新