gpt4 book ai didi

reactjs - 当 props 数据通过 React hooks 改变时,我想要重新渲染,但我得到了无限的重新渲染

转载 作者:行者123 更新时间:2023-12-03 14:15:26 27 4
gpt4 key购买 nike

抱歉我的英语不好..但我需要你们的帮助!问题是我想在 EditField 组件中的 props 更改时重新渲染。

所以我尝试了两种方法,

首先,我尝试使用 useEffect 参数在 UseEffect Hooks 中,我尝试了 useEffect(() => {},[facils]... 像这样但是当我尝试这种方式时,我得到了无限的重新渲染......

所以我尝试了另一种方法,我将 GetDB 函数传递给 EditField 组件,当我编辑 Prop 数据时,我尝试调用 GetDBfunction。

但是它并没有达到我的预期......

你能给我一些建议吗..?

const GetDB = () => {
const [facils, setFacils] = useState([]);

useEffect(() => {
firebase
.firestore()
.collection("facils")
.get()
.then((snapshot) => {
const newFacils = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
// prevent firebase quote exceed
console.log("!!!!FB warniing!!!!");
setFacils(newFacils);
});
}, []);
return facils;
};

const FacilityLists = () => {
const facils = GetDB();
const [id, setId] = useState([]);
const [name, setName] = useState([]);
const [showEdit, setShowEdit] = useState(false);

...
...
return (
<div>
<div style={{ display: "flex", justifyContent: "space-evenly" }}>
<div>Id</div>
<div>시설이름</div>
</div>
<div>
{facils.length > 0 ? (
facils.map((item) => (
<ul key={item.id} onClick={() => EditItem(item.id, item.name)}>
{item.id} - {item.name}
</ul>
))
) : (
<p>there is no data</p>
)}
</div>
<div>
{showEdit ? (
<EditField
id={id}
name={name}
showSave={() => setShowEdit(false)}
handleChange={handleChange}
refreshData={() => GetDB}
/>
) : (
<CreateField />
)}
</div>
</div>

最佳答案

您不能从处理函数中调用 Hook 。您可以做的是实现并从 GetDB Hook 公开一个提取器并调用它。

还要确保在创建自定义 Hook 时,在名称前添加 use 前缀,因为它会告诉 React 应用 rules of hooks并警告您错误使用

const useGetDB = () => {
const [facils, setFacils] = useState([]);
const fetchData = () => {
firebase
.firestore()
.collection("facils")
.get()
.then((snapshot) => {
const newFacils = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
// prevent firebase quote exceed
console.log("!!!!FB warniing!!!!");
setFacils(newFacils);
});
}
useEffect(() => {
fetchData();
}, []);
return { facils, fetchData};
};

发布您可以像下面这样使用它

const FacilityLists = () => {
const {facils, fetchData} = useGetDB();
const [id, setId] = useState([]);
const [name, setName] = useState([]);
const [showEdit, setShowEdit] = useState(false);

...
...
return (
<div>
<div style={{ display: "flex", justifyContent: "space-evenly" }}>
<div>Id</div>
<div>시설이름</div>
</div>
<div>
{facils.length > 0 ? (
facils.map((item) => (
<ul key={item.id} onClick={() => EditItem(item.id, item.name)}>
{item.id} - {item.name}
</ul>
))
) : (
<p>there is no data</p>
)}
</div>
<div>
{showEdit ? (
<EditField
id={id}
name={name}
showSave={() => setShowEdit(false)}
handleChange={handleChange}
refreshData={() => fetchData()}
/>
) : (
<CreateField />
)}
</div>
</div>

关于reactjs - 当 props 数据通过 React hooks 改变时,我想要重新渲染,但我得到了无限的重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61955757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com