如何使用useEffect获取数据,然后根据React Js中选定的过滤器选项进行渲染



我使用useEffect获取数据,然后希望稍后根据过滤器选择更改或更新表,但问题是它正是呈现我从过滤器中选择的内容,而不是呈现以前选择的选项数据。例如,如果我先从过滤器中选择挂起,然后再解析,则它将在解析时在选择时呈现挂起。

我不知道我在哪里犯错误。

QueryView.js

import { useEffect, useState } from 'react';
const QueriesView = () => {
const [queryData, setqueryData] = useState([])
const [status, setStatus] = useState("Pending")
const [data,setdata] = useState([])
const getStatus = (e) => {
setStatus(e.target.value)
setdata( queryData.filter(ele=> ele.querystatus === status))
}
useEffect(() => {
let url = "https://script.google.com/macros/s/AKfycbykZx2qtz39U5j8TwDRVuziKfoLzF6YkYvDL6Ejoj822Vg9MPe1pDS9PX86IeP1Kzw82Q/exec?request=getQueriesData";
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setqueryData(json)
}
catch (err) {
console.log("catching error")
}
}
fetchData();
}, [])

return (
<>       
<div className='container mt-2'>
<div className='row'>
<select className="form-select form-select-sm" aria-label=".form-select-sm example"
name='status'
onChange={getStatus}
value={status.value}
>
<option value="Pending">Pending</option>
<option value="Resolved">Resolved</option>
<option value="Rejected">Rejected</option>
</select>
</div>
<table class="table table-hover table-sm">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th>
<th scope="col">Query Number</th>
<th scope="col">Email</th>
<th scope="col">Full Name</th>
<th scope="col">Phone No.</th>
<th scope="col">Status</th>
<th scope="col">Details</th>
</tr>
</thead>
<tbody>
{data.map(ele => (
<tr>
<th scope="row">{ele.querydate}</th>
<td>{ele.querynumber}</td>
<td>{ele.email}</td>
<td>{ele.firstname} {ele.lastname}</td>
<td>{ele.contact}</td>
<td>{ele.querystatus}</td>
<td><button type='button'>Details</button></td>
</tr>
))}
</tbody>
</table>
</div>
</>
)
}
export default QueriesView;

更新:useEffect中提取数据时,必须根据当前选择的状态再次过滤:


useEffect(() => {
let url =
"https://script.google.com/macros/s/AKfycbykZx2qtz39U5j8TwDRVuziKfoLzF6YkYvDL6Ejoj822Vg9MPe1pDS9PX86IeP1Kzw82Q/exec?request=getQueriesData";
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setqueryData(json);
// set filtered again
setdata(json.filter((ele) => ele.querystatus === status));
} catch (err) {
console.log("catching error");
}
};
fetchData();
}, []);

以下是一个工作示例:https://codesandbox.io/s/exciting-stitch-k11sdd?file=/src/QueriesView.js


使用.map()呈现项目列表时,必须始终提供一个密钥,以便React能够识别相应的条目:https://reactjs.org/docs/lists-and-keys.html#keys

例如,使用数组索引(另一个字段比索引更好(:

{data.map((ele, index) => (
<tr key={index}>
<th scope="row">{ele.querydate}</th>
<td>{ele.querynumber}</td>
<td>{ele.email}</td>
<td>{ele.firstname} {ele.lastname}</td>
<td>{ele.contact}</td>
<td>{ele.querystatus}</td>
<td><button type='button'>Details</button></td>
</tr>
))}

最新更新