我有一个数组,我正试图在初始加载和onClick时对其进行洗牌。我的功能似乎在工作,但除非有一个页面阅读器,否则就看不见了。
我正在努力解决的两个问题:
-
我想在初始加载时进行混洗,但除非有重读程序,否则混洗不会发生。
-
我想在按下按钮时进行混洗,但除非有重新发送程序,否则混洗不会发生。
这是我的CodeSandbox
感谢
import React, {
useEffect,
useState
} from "react";
const myArray = [{
name: "cat",
count: 0
},
{
name: "dog",
count: 0
},
{
name: "hamster",
count: 0
},
{
name: "lizard",
count: 0
}
];
function shuffle(arra1) {
var ctr = arra1.length,
temp,
index;
while (ctr > 0) {
index = Math.floor(Math.random() * ctr);
ctr--;
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
return arra1;
}
function App(props) {
const [list, setList] = useState(myArray);
useEffect(() => {
const mountArray = shuffle(myArray);
setList(mountArray);
}, []);
function handleShuffle() {
const changes = shuffle([...list]);
setList(changes);
console.log("Shuffle", myArray, changes);
}
return (
<div>
{list.map((x, index) => (
<div key = {x.name + x.index}>
{x.name} - {x.count}
<button onClick={() => setList([...list], (x.count = x.count + 1))}>
+
</button>
</div>
))}
<button onClick={handleShuffle}>
Shuffle
</button>
</div>
);
}
export default App;
HAI我在App.js 中做了一些更改
import React, { useEffect, useState } from "react";
const myArray = [
{ name: "cat", count: 0 },
{ name: "dog", count: 0 },
{ name: "hamster", count: 0 },
{ name: "lizard", count: 0 }
];
function shuffle(arra1) {
var ctr = arra1.length,
temp,
index;
while (ctr > 0) {
index = Math.floor(Math.random() * ctr);
ctr--;
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
return arra1;
}
function App(props) {
const [list, setList] = useState(myArray);
useEffect(() => {
const mountArray = shuffle(myArray);
setList(mountArray);
}, []);
function handleShuffle() {
const changes = shuffle([...list]);
setList(changes);
console.log("Shuffle", myArray);
}
return (
<div>
{list.map((x, index) => (
<div key={x.name + x.index}>
{x.name} - {x.count}
<button onClick={() => setList([...list], (x.count = x.count + 1))}>
+
</button>
</div>
))}
<button onClick={handleShuffle}>Shuffle</button>
</div>
);
}
export default App;
您的setList函数用于修改数组,并返回一个新数组,其中包含搅乱的值,因此您需要在非初始渲染时应用该函数。
useEffect(() => {
setList(shuffle(myArray))
}, []);
Html只有在状态发生更改时才会更改,因此在组件内部创建一些状态,并在每次更新Html时更新它。
function App(props){
const [myArray, setMyArray] = useState([])
// rest of the code
}