状态更改时,React类不会更新

时间:2020-01-22 11:16:35

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

我正在制作一款游戏,在其中需要对选定(按下)的物品使用不同的样式。如果单击该div,我试图将“ selected”类附加到div。换句话说,我有一个状态:

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

以及何时

pressedGifId === gifId

然后我应该将“ selected”类附加到我的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>;
}

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

f12 view

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

console view

我的目标:

1)单击更改状态(pressedGifId)

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

UPDATE2:

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

我将光卡置于一种状态(一个钩子),并在第一次加载时将其设置(当光卡阵列长度为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>
      );
   }



2 个答案:

答案 0 :(得分:2)

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;

答案 1 :(得分: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