【发布时间】: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