React Hooks:立即在加载时随机播放数组,然后单击onClick

问题描述

我有一个数组,试图在初始加载和onClick上进行随机播放。我的功能似乎正常工作,但是除非重新渲染页面,否则这些功能不可见。

我要解决的2个问题:

  1. 我想在初始加载时随机播放,但是除非重新渲染,否则不会发生随机播放。

  2. 我想在按下按钮时进行随机播放,但是除非重新渲染,否则不会发生随机播放。

这是我的CodeSandbox

谢谢

import React,{
  useEffect,useState
} from "react";

const myArray = [{
    name: "cat",count: 0
  },{
    name: "dog",{
    name: "hamster",{
    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;

解决方法

我在App.js中做了一些更改

<img src="../../static/images/${filename}">
,

您的setList函数用于修改数组并返回带有改组值的新数组,因此您需要将该函数应用于非初始渲染。

 useEffect(() => {
    setList(shuffle(myArray))     
  },[]);
,

HTML仅在状态发生变化时才会发生变化,因此请在组件内部进行某种状态更改,并在每次要更新html时进行更新。

function App(props){
    const [myArray,setMyArray] = useState([])

    // rest of the code
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...