当事件处理程序被触发时,钩住useState吗?

时间:2020-09-26 20:27:16

标签: javascript reactjs react-hooks use-state

onCardLeftScreen事件处理程序触发控制台日志功能,但是不使用setState挂钩更新状态吗?我已经测试过,这是按预期运行的onClick函数的问题。

反应代码:

//sets initial cards within the queue
  const [cardQueue, setCardQueue] = useState([Data[0], Data[1], Data[2]]);

  //sets the index of card that will be pushed into queue
  const [cardQueueLength, setCardQueueLength] = useState(Data.length - 1);

  const autoplayChange = () => {
    setSlideShow(!slideShow);
    console.log("playing!");
  };

  const CardLeftScreen = () => {
    //iterates through cards(sets up loop)
    setCardQueueLength(
      cardQueueLength < Data.length - 1 ? cardQueueLength + 1 : 0
    );

    //removes card from front of queue
    cardQueue.shift();

    //pushes a card to back of queue
    cardQueue.push(Data[cardQueueLength]);

    //sets slideshow to true
    setSlideShow(true);

    //console logs cards in arrays and the index of the card being pushed to back of queue
    console.log(cardQueue);
    console.log(cardQueueLength);
  };

  return (
    <div className="cardStyles">
      {cardQueue.map((Projects, index) => {
        return (
          <TinderCard
            key={Projects.workName}
            preventSwipe={["up", "down"]}
            onCardLeftScreen={CardLeftScreen}
            className="Cards"
          >
            <Carousel
              showThumbs={false}
              infiniteLoop={true}
              swipeable={false}
              emulateTouch={false}
              showStatus={false}
              autoPlay={slideShow}
              dynamicHeight={false}
            >
              <div className="image-iframeContainer">
                {Projects.Images &&
                  Projects.Images.map((Image, index) => {
                    return (
                      <div key={Image} className="image-iframeContainer">
                        <img alt="Images of web apps" src={Image} />
                      </div>
                    );
                  })}
              </div>
            </Carousel>
            <h1>{Projects.workName}</h1>
            {Projects.workTech.map((Tech, index) => {
              return (
                <p key={Tech} className="techList">
                  {Tech}
                </p>
              );
            })}
            <div className="descriptionContainer">
              <p className="description">{Projects.workDescription}</p>
            </div>
          </TinderCard>
        );
      })}
      <button className='cardLeftScreenButton' onClick={CardLeftScreen}>click for onCardLeftScreen desired funtion</button>
    </div>
  );

我还设置了 Sandbox 以更好地显示我的问题,希望有人能找到解决方案,我的项目已经快完成了。使用的API为React-Tinder-Card

4 个答案:

答案 0 :(得分:1)

每当您在函数中设置状态时,它不会立即更新,只有在事件处理程序退出函数后,您才能看到更改。

我认为您的代码是正确的,请在该功能之后尝试控制台日志,该功能将向您显示预期的结果,如果要使用更新的值,请使用以下变量

[[index] as any,1]

答案 1 :(得分:1)

您正在直接更改状态数组,而不是复制它并影响那个数组。这意味着React认为您的数组实际上并没有改变。请考虑以下更改:

const {useState} = React;

const mockData = [
    {title: "Foo", description: "Hello World!"},
    {title: "Bar", description: "Fizz Buzz!"},
    {title: "Cool", description: "More Stuff!"}
];

const MyComponent = () => {
    const [cards, setCards] = useState([mockData[0], mockData[1], mockData[2]]);
    const [nextDataIndex, setNextDataIndex] = useState(mockData.length - 1);

    const onCardLeftScreen = () => {
        const newNextDataIndex = nextDataIndex < mockData.length - 1 ? nextDataIndex + 1 : 0;

        const newCards = [...cards];
        newCards.shift();
        newCards.push(mockData[newNextDataIndex]);

        setNextDataIndex(newNextDataIndex);
        setCards(newCards);
    };

    return (
        <div>
            <div>Num cards: {cards.length}</div>
            <div className="card-container">
                {cards.map(card => (
                    <div key={card.title} className="card">
                        <div>{card.title}</div>
                        <div>{card.description}</div>
                    </div>
                ))}
            </div>
            <button onClick={onCardLeftScreen}>Swipe Left</button>
        </div>
    );
};

const App = () => (
    <MyComponent />
);

ReactDOM.render(
    <App/>,
    document.getElementById("app")
);
.card-container {
  width: 100px;
  height: 100px;
  position: relative;
}
.card {
  background-color: #0000AA;
  color: #ffffff;
  padding: 0.2em;
  width: 50px;
  height: 50px;
  box-shadow: 2px 2px black;
  position: absolute;
  top: 0;
  left: 0;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="app"></div>

答案 2 :(得分:1)

尝试类似这样的方法。您直接改变状态是不好的,可能导致各种副作用和不幸,这可能是您连续两次看到同一张卡片,滞后等的原因。

GET https://graph.microsoft.com/v1.0/drives/{driveID}/list/columns"

答案 3 :(得分:1)

该问题是由于所使用的键不是唯一的事实引起的,onClick函数导致刷新刷新Dom而默认情况下没有onCardLeftScreen函数。将Tindercard的密钥设置为key={Projects.workName + Math.random()}可解决问题,因为react知道何时刷新。谢谢大家指出状态突变并不能解决我的问题,但是可以使我的代码更干净