【问题标题】:Component not re-rendering even after state changed即使在状态更改后组件也不会重新渲染
【发布时间】:2022-11-04 14:49:48
【问题描述】:

我在反应中有这个组件,即使在状态改变之后反应组件也不会重新渲染。

import { useState, useEffect } from "react";

const Game = (props) =\> {

    const [pokemonData, setPokemonData] = useState([]);
    
    const shufflePokemon = () => {
        console.log("pokemon is shuffling....")
        let temp = pokemonData;
        for (let i = temp.length - 1; i >= 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var t = temp[i];
            temp[i] = temp[j];
            temp[j] = t;
        }
        setPokemonData(temp);
        console.log(pokemonData);
    }
    
    useEffect(() => {
        setPokemonData(props.data);
    }, [props.data])
    
    return (
        <div>
            {console.log("rendering")}
            {
                pokemonData.length === 0 ? null :
                    pokemonData.map((curr) => {
                        return (
                            <div onClick={shufflePokemon} key={curr.id} >
                                <img src={curr.image} />
                                <p>{curr.name}</p>
                            </div>
                        )
                    })
            }
        </div>
    )

}

我知道状态已经改变,因为当我 console.log(pokemonData) 它向我显示新的 pokemon 数据的洗牌列表时。 但是组件没有重新渲染。

当我单击任何包含 pokemon 图像的 div 时,我希望它们也能随机播放,但即使状态已更改,组件也不会重新渲染,因此它们不会因状态更改而改变。

【问题讨论】:

    标签: javascript reactjs frontend


    【解决方案1】:

    因为pokemonData 和初始化数据是同一个引用。你必须克隆pokemonData 尝试像这样更改shufflePokemon

    const shufflePokemon = () => {
        console.log("pokemon is shuffling....")
        let temp = [...pokemonData];
        for (let i = temp.length - 1; i >= 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var t = temp[i];
            temp[i] = temp[j];
            temp[j] = t;
        }
        setPokemonData(temp);
    }
    
    

    【讨论】:

      【解决方案2】:

      shufflePokemon 函数中尝试let temp = [...pokemonData]; 而不是let temp = pokemonData;

      这里发生的是你直接改变状态,当你试图设置调用setPokemonData的数据时,你给出的引用与参数相同。 React 不会识别状态变化,因为之前的状态和当前的状态指向同一个引用。

      当您使用 ... 解构数组时,temp 将引用一个新数组。

      【讨论】:

        猜你喜欢
        • 2020-02-18
        • 1970-01-01
        • 2019-06-29
        • 2021-05-07
        • 2021-07-26
        • 1970-01-01
        • 1970-01-01
        • 2019-05-31
        • 2019-11-24
        相关资源
        最近更新 更多