避免使用useEffect钩子无限循环



每次使用该表单添加新项目时,我都尝试显示更新的项目列表。使用 useEffect 钩子,我一直陷入无限循环,导致页面崩溃。 我不确定如何添加某种验证,仅在添加新项目时才要求重新渲染我的组件。

@app.route('/assets')
def get_assets():
print('this is a test')
cursor = assets.find() 
list_cur = list(cursor)
assets = dumps(list_cur)
return assets
<小时 />
function Assets() {
const [currentAsset, setCurrentAsset] = useState(0);
useEffect(() => {
(async () => {
const result = await fetch('/assets')
const data = await result.json()
setCurrentAsset(data)
})()
}, [currentAsset]);


return (
<div>
<header>
<table className="table table-striped">
<thead>
<tr>
<th>Ip Address</th>
<th>Asset Type</th>
<th>Username</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
{Object.values(currentAsset).map((item, index) => (
<tr key={item._id? item._id.$oid: null}>
<td>{item.ip_address}</td>
<td>{item.asset_type}</td>
<td>{item.username}</td>
<td>{item.notes}</td>
</tr>
)
)}
</tbody>
</table>
</header>
</div>
);
}
export default Assets;

注意:我想呈现更新数据,而无需在每次添加新项目时重新加载页面。我正在尝试实现与此演示相同的结果:https://taniarascia.github.io/react-hooks/有没有只有钩子的方法?

在"useEffect"中,它将更新状态"currentAsset"。然后它将触发组件再次重新渲染。 结果,"useEffect()"将再次运行并更新状态。接下来,整个过程再次重复,你被困在一个无限循环中。

useEffect(() => {
(async () => {
const result = await fetch('/assets')
const data = await result.json()
setCurrentAsset(data)
})()
}, []);

您无法在其中更新useEffect依赖项中的state variable您可以进行多个useEffects您应该先在空useEffect中检索它,然后再进行另一个以侦听currentAsset更改

useEffect(() => {
/// this will work as componentDidMount 
// will be called only once at the first after rendering the component
(async () => {
const result = await fetch('/assets')
const data = await result.json()
setCurrentAsset(data)
})()
}, []);
useEffect(() => {
// listen on the change of the currentAsset here but DONOT update it here
}, [currentAsset]);

通常,查询使项目发生变化,我们应该侦听查询的变化,并更新项目。 只需添加查询状态即可使逻辑清晰。


function Assets() {
const [currentAsset, setCurrentAsset] = useState({});
const [query, setQuery] = useState('');
useEffect(() => {
(async () => {
const result = await fetch('/assets?query=' + query)
const data = await result.json()
setCurrentAsset(data)
})()
}, [query]);

return (
<div>
<header>
<table className="table table-striped">
<thead>
<tr>
<th>Ip Address</th>
<th>Asset Type</th>
<th>Username</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
{Object.values(currentAsset).map((item, index) => (
<tr key={item._id? item._id.$oid: null}>
<td>{item.ip_address}</td>
<td>{item.asset_type}</td>
<td>{item.username}</td>
<td>{item.notes}</td>
</tr>
)
)}
</tbody>
</table>
</header>
</div>
);
}
export default Assets;

最新更新