在React.js中,将REST API调用保存在不同文件中可以通过以下步骤实现:
下面是一个示例:
在api.js文件中:
// api.js
export const getUser = async () => {
try {
const response = await fetch('/api/user');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
};
export const updateUser = async (userId, userData) => {
try {
const response = await fetch(`/api/user/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
});
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
};
在需要使用API的组件中:
// MyComponent.js
import React, { useEffect, useState } from 'react';
import { getUser, updateUser } from './api';
const MyComponent = () => {
const [user, setUser] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const userData = await getUser();
setUser(userData);
} catch (error) {
// Handle error
}
};
fetchData();
}, []);
const handleUpdateUser = async () => {
try {
const updatedUser = await updateUser(user.id, { name: 'New Name' });
setUser(updatedUser);
} catch (error) {
// Handle error
}
};
return (
<div>
{user ? (
<div>
<h1>{user.name}</h1>
<button onClick={handleUpdateUser}>Update User</button>
</div>
) : (
<p>Loading...</p>
)}
</div>
);
};
export default MyComponent;
在上面的示例中,api.js文件中定义了两个API调用函数:getUser和updateUser。在MyComponent组件中,通过调用getUser函数来获取用户数据,并在点击按钮时调用updateUser函数来更新用户数据。
领取专属 10元无门槛券
手把手带您无忧上云