简体   繁体   English

无法在函数内部设置状态(反应)

[英]cant set a state inside function (react)

Learning by coding, here i have simple graph, where are different datas such as current, all and filtered data, first code works fine, but i wanted to setState so i changed code a little (second code), if i uncomment 'setTest' it give 'Error: Too many re-renders.通过编码学习,这里我有一个简单的图表,不同的数据在哪里,例如当前,所有和过滤的数据,第一个代码工作正常,但我想 setState 所以我改变了一点代码(第二个代码),如果我取消注释'setTest'它给出'错误:重新渲染太多。 React limits the number of renders to prevent an infinite loop.' React 限制了渲染的数量以防止无限循环。 is there a fix to this or should i somehow use useEffect?有没有解决这个问题或者我应该以某种方式使用useEffect? and another question is why should i call function 'kk()', and not just reference to it 'kk' because when i use reference it give error 'Uncaught TypeError: Cannot read properties of undefined' but when calling function it wont give error, but then i have used reference to function without problem 'onClickNode={onClickNode}' .另一个问题是为什么我应该调用函数'kk()',而不仅仅是引用它'kk',因为当我使用引用时它会给出错误'Uncaught TypeError:无法读取未定义的属性'但是在调用函数时它不会给出错误,但后来我使用了对函数的引用,没有问题 'onClickNode={onClickNode}' 。

1: 1:

 import { Graph } from "react-d3-graph"; <Graph data={ hideData ? curentData ? allData : filteredData : allData } onClickNode={onClickNode} />

2: 2:

 import { Graph } from "react-d3-graph"; const [test, setTest] = useState<any>("testData1"); const kk = () => { // setTest("testData2") return curentData ? allData : filteredData; }; <Graph data={hideData ? kk() : allData} onClickNode={onClickNode} />

English is not my mother language so could be mistakes.英语不是我的母语,所以可能是错误的。

You should not call a state changing function within your rendering logic without some sort of condition.在没有某种条件的情况下,您不应在渲染逻辑中调用状态更改函数。 Without a condition to prevent a state change results in an infinite loop as you are seeing.如您所见,如果没有阻止状态更改的条件,则会导致无限循环。

One option you can try is call setTest("testData2") on a particular user action, like this:您可以尝试的一个选项是在特定用户操作上调用setTest("testData2") ,如下所示:

  const [test, setTest] = useState<any>("testData1");
 
  const kk = () => {
    return curentData ? allData : filteredData;
  };
  
  const onClickNode = () => {
    // Handle other click logic...
    setTest("testData2");
  };
  
  <Graph data={hideData ? kk() : allData} onClickNode={onClickNode} />

But without seeing more of that code, that option may not make sense for you.但是如果没有看到更多的代码,这个选项对你来说可能没有意义。

Another option would be to check the value of test before calling setTest("testData2") , like this:另一种选择是在调用setTest("testData2")之前检查test的值,如下所示:

  const [test, setTest] = useState<any>("testData1");
  
  const kk = () => {
    if (test !== "testData2") {
      setTest("testData2");
    }
    return curentData ? allData : filteredData;
  };
 
  <Graph data={hideData ? kk() : allData} onClickNode={onClickNode} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM