从使用状态更改变量其他变量正在功能组件中重置
Change variable from usestate other variable is getting reset in functional component
当我更新我的状态变量时,我的状态变量发生了变化,但我的所有其他变量都恢复到它们的初始值。我正在添加我的测试组件。
如果我删除 setTest 那么我的 combileFileData 在按下添加按钮后给出预期的值,但是当我使用 setTest 所以每次它都会给我 ['b]
const [pass, setPass] = React.useState([]);
let combineFileData = ["b"];
function showHandler() {
console.log("combine file data", combineFileData);
}
function addHandler() {
setPass(["a", "s"]);
combineFileData.push("a");
}
return (
<div>
<button onClick={showHandler}>Show</button>
<button onClick={addHandler}>Add</button>
</div>
);
}
您的 combineFileData
在每次渲染时都会“重新初始化”。因此它的行为就像它始终具有初始值一样。
为了使您的实施尽可能相同,您可以像这样使用 ref:
const combineFileData = useRef([“b”]);
function addHandler() {
setPass(["a", "s"]);
combineFileData.current.push("a");
}
当我更新我的状态变量时,我的状态变量发生了变化,但我的所有其他变量都恢复到它们的初始值。我正在添加我的测试组件。
如果我删除 setTest 那么我的 combileFileData 在按下添加按钮后给出预期的值,但是当我使用 setTest 所以每次它都会给我 ['b]
const [pass, setPass] = React.useState([]);
let combineFileData = ["b"];
function showHandler() {
console.log("combine file data", combineFileData);
}
function addHandler() {
setPass(["a", "s"]);
combineFileData.push("a");
}
return (
<div>
<button onClick={showHandler}>Show</button>
<button onClick={addHandler}>Add</button>
</div>
);
}
您的 combineFileData
在每次渲染时都会“重新初始化”。因此它的行为就像它始终具有初始值一样。
为了使您的实施尽可能相同,您可以像这样使用 ref:
const combineFileData = useRef([“b”]);
function addHandler() {
setPass(["a", "s"]);
combineFileData.current.push("a");
}