除非重新加载整个页面,否则从 django 后端插入的记录的反应代码不会在插入后立即更新
2024-01-06
30
import React from 'react' import { useEffect, useState } from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import './expensetable.css'
const ExpenseTable = () => { const [expenses, setExpenseData] = useState([]); const [url, setUrl] = useState('http://127.0.0.1:8000/api/expensetracker/');
console.log(expenses); useEffect(() => { const fetchData = async () => { try { const response = await fetch(url); const data = await response.json(); setExpenseData(data); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, [url]); return ( <div> <div className="container mt-2"> { expenses.map((expense, index) =>( <div className="row" key={index}> <hr /> <div className="container dataContainer"> <div className="row"> <p className='col-3 text-capitalize'>{index+1}</p> <p className='col-3 text-capitalize'>spender - {expense.spender}</p> <p className='col-3 text-capitalize'>spender amount - {expense.spender_amount}</p> <p className='col-3 text-capitalize'>spender date - {expense.spender_date}</p> <p className='col-3 text-capitalize'>category - {expense.category}</p> <p className='col-3 text-capitalize'>spent location - {expense.spent_location}</p> <p className='col-3 text-capitalize'>spender reason - {expense.spender_reason}</p> <p className='col-3 text-capitalize'>spender comment - {expense.spender_comment}</p> <p className='col-3 text-capitalize'>payment method - {expense.payment_method}</p> <p className='col-3 text-capitalize'>attachment - {expense.attachment ? expense.attachment
: 'false'}
)) } ) }export default ExpenseTable;
1个回答
您想要的解决方案有点高级。您获取的 API 数据仅执行一次,并且直到窗口重新加载或 JSX 重新连接时它都是相同的。
由于您正在使用 React,我可以推荐最流行的库 React Query 。您可以使用 过时时间 (数据过期时间)或 重新获取查询 来获取您请求的功能。
这些都是非常高级的主题。如果您是标准程序员,则需要 2 周的时间来实现它。
祝一切顺利。编码愉快!
新更新:
这可以用于正常用途。工作正常。但不推荐用于大型项目
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
const [reload, setReload] = useState(false);
useEffect(() => {
fetch('https://backend.com/data')
.then(response => response.json())
.then(data => setData(data));
}, [reload]);// Which means runs this function when reload value is changed// Which updates your data
const handleSubmit = () => {
// Perform your save operation here as per your method
setReload(!reload); // Reloads Data
};
return (
<div>
{/* Render your {data} here */}
<button onClick={handleSubmit}>Save</button>
</div>
);
}
export default MyComponent;
JOY SAM RAJ
2024-01-06