英文:
UseEffect called when check box is checked inside a nested flatlist
问题
以下是您要翻译的内容:
"所以我正在处理一个嵌套深层次的JSON数据,其中涉及到多个复选框。因此,每当我选中一个复选框时,都会调用 useEffect,我认为这不是正确的行为。
UseEffect函数:
我将嵌套的JSON传递给了依赖数组,因为当树的深处发生修改时,应该调用 useEffect,但它在每次选中和取消选中复选框时都会被调用。
useEffect(() => {
console.log("in");
}, [...fetchedData.map((item) => item.orderList.map((item) => item.orders))]);
复选框点击处理程序:
const checkboxHandler = useCallback((orderId, subId, id) => {
const x = orderId + "-" + subId + "-" + id;
if (checkedArr.indexOf(x) > -1) {
let filteredArray = checkedArr.filter((item) => item !== x);
setcheckedArr(filteredArray);
} else {
setcheckedArr([...checkedArr, x]);
}
}, []);
所以我是React Native的初学者,所以想知道我做错了什么,另一个问题是我是否以一种高效的方式呈现了嵌套的JSON。
欢迎任何帮助或建议,谢谢!"
英文:
so I'm working with a deeply nested JSON data where there are multiple checkboxes involved .So whenever I check a checkbox the use effect gets called which I don't think is the correct behavior
UseEffect function <br>
im passing the nested json to the dependency array since when there are modifications deep in the tree use effect should get called ,but it gets called on every check and uncheck of a checkbox
useEffect(() => {
console.log("in");
}, [...fetchedData.map((item) => item.orderList.map((item) => item.orders))]);
checkbox click handler
const checkboxHandler = useCallback((orderId, subId, id) => {
const x = orderId + "-" + subId + "-" + id;
if (checkedArr.indexOf(x) > -1) {
let filteredArray = checkedArr.filter((item) => item !== x);
setcheckedArr(filteredArray);
} else {
setcheckedArr([...checkedArr, x]);
}
}, []);
So I'm a beginner to react native ,so wanted to know what I'm doing wrong also another question would be am I rendering he flatlist in a efficient way for nested json .
Please find the snack link to test/play around
Any help or suggestions are welcome thank you
答案1
得分: 1
鉴于您在依赖数组中使用了扩展运算符,每次状态更新时都会重新渲染,对于您的情况,保持这样的写法应该没问题:
useEffect(() => { console.log("in"); }, [fetchedData]);
除非您需要检查特定元素,在这种情况下,请在另一个钩子useMemo
中进行筛选。
英文:
Since you are using the spread operator in the dependency array, it will rerender everytime the state is updated, in your case, it should be completely fine to leave it like this:
useEffect(() => { console.log("in"); }, [fetchedData]);
unless you need to check specific elements, and in this case do the filters in another hook useMemo
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论