简体   繁体   English

为什么更改内部内部函数时外部变量不会动态更改?

[英]Why outer variable isn't change dynamically when changing inside inner functions?

I have this code which i use in react. 我有我在反应中使用的这段代码。 The important things here is that the function returns two kfl s, and the first has kezdet: 3 , the second has kezdet: 2 . 这里重要的是该函数返回两个kfl ,第一个具有kezdet: 3 ,第二个具有kezdet: 2 But the lnkfl don't have this numbers. 但是lnkfl没有这个数字。 My idea was to create an outer scoped variable, the map sets it, then the end of the return, it will be the correct value, then, when the map of lnkfl processes the new element, the variable is set the new value, just before the return on the end needs it. 我的想法是创建一个外部作用域变量,将其设置为映射,然后返回的结尾将是正确的值,然后,当lnkfl的映射处理新元素时,将变量设置为新值,在最终需要回报之前。 But it isn't. 但事实并非如此。

 feladatsorok = () => { const {nézet, kozvetlenFl, feladatok, lnkfl} = this.state let kezdet; return lnkfl.map(lnkfl => { const sor = () => { return kozvetlenFl[nézet] .filter(kfl => kfl.lnkfl === lnkfl) .map(kfl => { kezdet = kfl.kezdet //i want to use kfl.kezdet... const fl = () => { return feladatok[nézet] .filter(fl => fl.legnagyobbSzuloId === kfl.legnagyobbSzuloId) .map(fl => { return <div style={{ gridColumn: `${fl.sorkezdet + 1 } / span ${fl.hossz}`, gridRow: fl.szint + "/ span 1", border: "1px solid", overflow: "hidden" }}> {fl.nev} </div> }) } return <div style = {{ gridColumn: `${kfl.dk + 1} / span ${kfl.hossz}`, backgroundColor: "purple", gridRow: "1 / 2", display: "grid", gridTemplateColumns: `repeat( ${kfl.hossz} , 1fr)`, gridTemplateRows: "repeat(" + kfl.sorok + ", 1fr)" }}> {fl()} </div> }) } console.log(kezdet) return <div style = {{ gridRow: kezdet + " / span 1", //...here gridColumn: "start", display: "grid", gridTemplateColumns: feladatfilternezetalapjan(), gridTemplateRows: "1fr", backgroundColor: "yellow" }}> {sor()} </div> }) } 

The console returns undefined first, then 3. The expected values are 3, and 2. Inside the code snippet, i was shown that where the value of kezdet came from, and at the end, where i want to use it. 控制台首先返回undefined,然后返回3。期望值分别为3和2。在代码段中,向我显示了kezdet的值来自何处,最后,我想使用它。 What's the solution for this problem? 这个问题有什么解决方案?

Well, you're essentially setting kezdet inside a .sor . 好吧,您实际上是在.sor设置kezdet But you're calling the .sor after you first use your kezdet -- 但是,我们在调用.sor你第一次使用 kezdet -

return <div style = {{            
  // for the first 'lnkfl.map' element, 'kezdet' is still undefined here         
  gridRow: kezdet + " / span 1", 
  gridColumn: "start",
  display: "grid",
  gridTemplateColumns: feladatfilternezetalapjan(),
  gridTemplateRows: "1fr",
  backgroundColor: "yellow"
  }}>
     {sor()} // setting 'kezdet' for the first time
  </div>

So your kezdet is always "one value late". 因此,您的kezdet总是“晚一kezdet ”。

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

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