【问题标题】:How use useEffect correctly with array如何正确使用 useEffect 与数组
【发布时间】:2021-08-05 18:19:44
【问题描述】:

就像我在这里发帖:how choice when useEffect is executed in React 我想使用 useEffect() 和一个数组,必须存储后才能重用。但我不知道如何在 React 中做到这一点。我尽量让我的问题清楚。

import "./styles.css";
import { useEffect } from "react";
let list = [];
function Buffer(props) {
  let init = null;
  if (list.length === 0) {
    console.log("only once go here and that what I want !!!");
    list.push(init);
  }
  return <Comp title={props.title}>{list[0]}</Comp>;
}

function Comp({ children, ...props }) {
  useEffect(() => {
    children = ["truc"];
    console.log(props.title, "Comp + useEffect():", children);
  }, []);
  console.log(props.title, "Comp:", children);
  return (
    <div>
      {props.title} + {children}
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <Buffer title="step 0" />
      <Buffer title="step 1" />
    </div>
  );
}

噩梦:输出 呐喊我的梦想......

only once go here and that what I want !!! index.js:27:25
step 0 Comp: null index.js:27:25
step 1 Comp: null index.js:27:25
step 0 Comp + useEffect(): 
Array [ "truc" ]
index.js:27:25
step 1 Comp + useEffect(): 
Array [ "truc" ]

梦想:输出 我梦想中的输出目标是 第 1 步,保留truc,一定不要null,这是我的梦想变成噩梦的地方。

only once go here and that what I want !!! index.js:27:25
step 0 Comp: null index.js:27:25
step 1 Comp: Array [ "truc" ] index.js:27:25
step 0 Comp + useEffect(): 
Array [ "truc" ]
index.js:27:25
step 1 Comp + useEffect(): 
Array [ "truc" ]

运行中的 sn-p https://codesandbox.io/s/busy-cookies-yvq16?file=/src/App.js:0-716

【问题讨论】:

    标签: javascript arrays reactjs use-effect


    【解决方案1】:

    首先,我不完全理解你想要做什么,但你犯的一个错误是操纵道具。任何类型的道具都不应该直接修改,而是使用状态变量。此外,当渲染多个相同类型的元素时,它们必须有一个 prop 来唯一标识它们中的每一个。

    在给定的沙箱中,我进行了这些更改。看看这个。希望它会有所帮助。

    Sandbox

    【讨论】:

    • 怎么可能,在您的沙盒中,“第 1 步”看到在“第 0 步”的 useEffect() 被触发并物理设置之前初始化的数组? O_O 我会理解 step 0 > step 0 useEffect > step 1(具有所需值)> step 1 useEffect
    • 感谢您的回答,但我认为这不是我想要的。在我的想法中,我的第二个 &lt;Buffer/&gt; 必须使用由第一个 &lt;Buffer/&gt; 初始化的数组内容,如果我的示例不是很简单,请原谅。
    猜你喜欢
    • 2020-07-15
    • 2021-11-16
    • 2021-01-24
    • 2021-09-24
    • 1970-01-01
    • 2020-11-29
    • 2020-01-23
    • 1970-01-01
    • 2022-07-16
    相关资源
    最近更新 更多