【问题标题】:React class does not update when state changes状态更改时 React 类不更新
【发布时间】:2020-05-08 12:56:40
【问题描述】:

我正在制作一个游戏,我需要为选定(按下)项目提供不同的风格。如果单击该 div,我正在尝试将“选定”类附加到 div。换句话说,我有一个状态:

const [pressedGifId, gifPressed] = useState(null);

什么时候

pressedGifId === gifId

然后我应该将“选定”类附加到我的 div。 这是我的简化代码:

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

export default function Game() {
  const addedToGameGif = [];

  const [pressedGifId, gifPressed] = useState(null);
  const [photoCards] = useState([]);

  useEffect(() => {
    console.log(pressedGifId);
  }, [pressedGifId]);

  if (photoCards.length === 0) {
    for (let i = 0; i < 5; i += 1) {
      addedToGameGif.push([i, 'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg']);
    }
  }

  addedToGameGif.map(item =>
    photoCards.push(
      <div key={item[0]}>
        <div
          onClick={() => gifPressed(`gif${item[0]}`)}
          className={`${pressedGifId === `gif${item[0]}` && 'selected'}`}
        >
          <img src={item[1]} alt="bla" width="300" height="180" />
        </div>
        <br />
      </div>,
    ),
  );
  return <div>{photoCards}</div>;
}

我看不到根据状态更新的类:(它保持为空)

但我在控制台中获得了更新的状态(我在 useEffect 中打印它):

我的目标:

1) 单击时更改状态 (pressedGifId)

2) 如果pressedGifId 匹配当前映射的item id (gif${item[0]}),则将“selected”类添加到div

更新2:

提供的解决方案对我不起作用,因为我的照片卡是随机挑选的照片,并且使用提供的解决方案,每次点击时照片都会变成新的随机挑选的照片(我不想这样)。但这让我得到了正确的答案:

我将 photoCards 置于一个状态(钩子)并在第一次加载时设置它(当 photoCards 数组长度为 0 时)。它阻止重新加载并且类工作。

这里是更新的代码:

    export default function Game(props) {

    const [pressedGifId, setGifPressed] = useState(null);
    const [gifCards, setGifCards] = useState([]);

    useEffect(() => {
        if (gifCards.length === 0) 
          setGifCards(randGen.getGifArray());
    }

      const renderCards = () =>
      gifCards.map((item, index) => {
      const gifId = `gif${item[0]}`;

      return (
        <div key={item[0]}>
          <div
            onClick={() => setGifPressed(gifId)}
            onKeyPress={() => setGifPressed(gifId)}
            role="button"
            tabIndex="0"
            className={`card ${getClass(gifId)}`}
          >
            <img
              src={item[1]}
              alt={txtCards[index][1]}
              width="300"
              height="180"
            />
          </div>
        </div>
      );
    });

     return (
       <div>
          {renderCards()}
        </div>
      );
   }



【问题讨论】:

  • 你只想根据你的 onClick 权限给 className ???
  • 是的,我想在点击时改变状态(pressedGifId),如果pressedGifId与当前映射的项目ID匹配,则将类“selected”添加到div。
  • 好的,我会更新我的答案等待

标签: javascript reactjs state use-effect use-state


【解决方案1】:
import React, { useState, useEffect } from 'react';

const Game = () => {

  //here we are passing our gif data 
  const gifData = [
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg',
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg',
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg',
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg',
    'http://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg' 
  ]

  // pressedGifId : for gifId selection
  const [pressedGifId, setGifPressed ] = useState(0);

  // renderPhotoCards : this function return all cards 
  // onClick :   setGifPressed to clicked gifId 
  // className : if our index of perticuler gif match with pressedGifId then we are setting it as selected

  const renderPhotoCards = () => 
    gifData.map(( item , index )  => (
      <div key={index}>
        <div
          onClick={() => setGifPressed(index)}
          className={  pressedGifId === index ? `gif${index} selected` : `gif${index}`  }
        >
          <img src={item} alt="bla" width="300" height="180" />
        </div>
        <br />
      </div>
    )
  )

  return renderPhotoCards()

}

export default Game;

【讨论】:

  • 是的,我试过了。它返回空类''。我也试过 className={${pressedGifId}} 但返回 class=null
  • 如果您还有任何问题,请告诉我。
  • 等等,不,它只是在元素中添加了gif${item[index]},但仍然没有选中
  • 试试这个,如果你有问题,请告诉我
【解决方案2】:

这是我改变的那一行。

className={pressedGifId === `gif${item[0]}` ? "selected" : ""}

整个代码。

import React, { useState, useEffect } from "react";
import "./styles.css";
export default function Game() {
  const addedToGameGif = [];

  const [pressedGifId, gifPressed] = useState(null);
  let photoCards = [];

  useEffect(() => {
    console.log("->", pressedGifId);
  }, [pressedGifId]);

  if (photoCards.length === 0) {
    for (let i = 0; i < 5; i += 1) {
      addedToGameGif.push([
        i,
        "https://petapixel.com/assets/uploads/2019/06/manipulatedelephant-800x534.jpg"
      ]);
    }
  }

  photoCards = addedToGameGif.map(item => (
    <div key={item[0]}>
      <div
        onClick={() => gifPressed(`gif${item[0]}`)}
        className={pressedGifId === `gif${item[0]}` ? "selected" : ""}
      >
        <img src={item[1]} alt="bla" width="300" height="180" />
        {console.log(item)}
      </div>
      <br />
    </div>
  ));

  console.log("-", photoCards, addedToGameGif);
  return <div>{photoCards}</div>;
}

这是有效的。我试过了,看看这个JS snippet

【讨论】:

  • 谢谢,它对我不起作用,因为我的照片卡是随机挑选的照片,并且使用此解决方案,照片在每次点击时都会发生变化(我不想这样)。但这让我得到了正确的答案:我将 photoCards 置于一个状态(钩子)并将其设置为第一次加载(当 photoCards 数组长度为 0 时)。它阻止重新加载并且类工作。谢谢,。
  • 很高兴您找到了解决方案。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2018-09-21
  • 2020-09-28
  • 1970-01-01
  • 2020-07-18
  • 2019-02-19
  • 1970-01-01
  • 2019-12-29
相关资源
最近更新 更多