这里有一个简单的组件,其中我将一个名为input的状态变量设置为一个数字数组的值。然后,在useEffect中调用一个函数,将初始状态数组随机化,并将结果放入一个名为output的新状态变量中。
我需要输入数组保持相同的顺序。但是,当我调用shuffleArray函数时,它正在发生变异。
我认为无法更改作为参数传递的变量所持有的值,如果JavaScript支持通过引用传递的话,这是可能的。
const App = () => {
const [input, setInput] = React.useState([90, 32, 28, 8, 21, 24, 64, 92, 45, 98, 22, 21, 6, 3, 27, 18, 11, 56, 16, 42, 36, 2, 60, 38, 24, 8, 16, 76, 62, 14, 84, 32, 24, 18, 8, 5, 25, 68, 65, 26, 22, 2, 52, 84, 30, 8, 2, 90, 5, 34, 56, 16, 42, 36]);
const [output, setOutput] = React.useState([]);
const shuffleArray = (array) => {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
React.useEffect(() => {
setOutput(shuffleArray(input));
}, [])
return (
<div>
[
{
input.length > 0 ?
input.map((n, i) => (
<span key={i}>
{ (i? ", " : "") + n }
</span>
))
:
"No array..."
}
]
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
发布于 2021-12-17 19:31:22
输入被改变了,因为这就是逐值传递的工作方式。原语不能在没有重新分配的情况下发生变异。但是,当涉及对象(和数组,如本例)时,对象的属性可以在不重新分配的情况下发生变化。
如果要保持输入不变,可以使用Array.from并操作数组的副本。
const App = () => {
const [input, setInput] = React.useState([90, 32, 28, 8, 21, 24, 64, 92, 45, 98, 22, 21, 6, 3, 27, 18, 11, 56, 16, 42, 36, 2, 60, 38, 24, 8, 16, 76, 62, 14, 84, 32, 24, 18, 8, 5, 25, 68, 65, 26, 22, 2, 52, 84, 30, 8, 2, 90, 5, 34, 56, 16, 42, 36]);
const [output, setOutput] = React.useState([]);
const shuffleArray = (array) => {
const shuffled = Array.from(array);
for (let i = shuffled.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
let temp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = temp;
}
return shuffled;
}
React.useEffect(() => {
setOutput(shuffleArray(input));
}, [])
return (
<div>
[
{
input.length > 0 ?
input.map((n, i) => (
<span key={i}>
{ (i? ", " : "") + n }
</span>
))
:
"No array..."
}
]
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
发布于 2021-12-17 19:58:57
Javascript实际上通过“引用的副本”传递对象和数组,如下所示:https://stackoverflow.com/a/13104500/17704187
因此,您的shuffleArray函数实际上改变了输入数组的内容。
https://stackoverflow.com/questions/70398031
复制相似问题