UseEffect在嵌套的FlatList中选中复选框时被调用

huangapple go评论51阅读模式
英文:

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(() =&gt; {
    console.log(&quot;in&quot;);
  }, [...fetchedData.map((item) =&gt; item.orderList.map((item) =&gt; item.orders))]);

checkbox click handler

  const checkboxHandler = useCallback((orderId, subId, id) =&gt; {
    const x = orderId + &quot;-&quot; + subId + &quot;-&quot; + id;
    if (checkedArr.indexOf(x) &gt; -1) {
      let filteredArray = checkedArr.filter((item) =&gt; 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(() =&gt; { console.log(&quot;in&quot;); }, [fetchedData]);

unless you need to check specific elements, and in this case do the filters in another hook useMemo .

huangapple
  • 本文由 发表于 2023年6月11日 22:51:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定