reactjs - React Hooks - 使用帖子中的新数据刷新页面上的一些数据
问题描述
我有一个仅在安装时才获取数据的组件。理想情况下,我只想进行一次此调用,因为它正在获取大量数据。当我发出发布请求时,我会收到想要在页面上显示的新数据并乐观地更新 UI。我不想再次重新获取数据,因为这是一个昂贵的调用,而是只想更新更改的数据。我可以创建一个 API 端点,我调用它来获取有关更新的必要数据,但为什么不使用从发布请求中收到的数据来更新数据呢?
示例代码:
const App = () => {
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const [alert, setAlert] = useState(null);
// data states
const [user, setUser] = useState(null);
const [account, setAccount] = useState(null);
const [key, setKey] = useState(null);
const [externalAccount, setExternalAccount] = useState(null);
const [showModal, setShowModal] = useState(false);
// fetch data upon component mount
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
// Get data for working with accounts
const res = await get(
'/api/v1/account'
);
setUser(res.data.user);
setAccount(res.data.account);
setKey(res.data.key);
setExternalAccount(res.data.external_account);
} catch (e) {
setError(e);
}
setLoading(false);
};
fetchData();
}, []);
const createAccount = async params => {
setLoading(true);
try {
// send request
const res = await post(
'/api/v1/account',
params
);
// set updated account data
setAccount(res.data.account); //doesn't update on the page. I could call a refetch in the above useEffect but not ideal. Any other options?
// set success alert
setAlert('Your account was created successfully.');
// update loading state
setLoading(false);
} catch (e) {
setAlert(e.message);
setLoading(false);
}
};
// Define page renders
if (error) return <ErrorComponent />;
if (loading) return <Loader />;
return (
<>
<h1>Account</h1>
{account &&
<div>
//display information using state information on user and account
</div>
}
{showModal &&
<CreateModal
toggleModal={setShowModal}
createAccount={createAccount}
user={user}
account={account}
/>
}
</>
);
}
const CreateModal = ({ toggleModal, createAccount }) => {
const handleSubmit = e => {
e.preventDetault();
const params = // set up params for post request
createAccount(params)
return (
<form onSubmit={e => handleSubmit(e)}>
//form code here
</form>
)
}
解决方案
推荐阅读
- linux - ip 表 127.0.0.1 到 ipv4.fiddler
- python - 如何从 file.txt 在 matplotlib 中使用文本列与数字列构建图表?
- monaco-editor - 使用诊断时在模型中存储信息并一起悬停
- python - 过滤条件在熊猫中不起作用
- excel - 尝试更新现有文本框,但收到“需要对象”错误
- macos - macos中已挂载驱动器的路径
- node.js - 错误:内部/模块/cjs/loader.js:896 throw err 错误:找不到模块 'C:\Users\Administrator\Desktop\arij\first'
- c# - How to download files from a database, and get them as image in Asp.net core MVC?
- sql - 按键将记录分组到具有多列的单行中
- r - ggplot2 图中 webdings 符号的图例符号