为什么setState在第一次调用时不起作用?

时间:2019-11-21 15:12:30

标签: javascript reactjs react-hooks

我有一个通过按钮调用的函数,该函数内部是我的setSelected夹着selectedCards的代码,我的代码取决于此更改是否起作用,但更改仅在第二次发生我单击按钮。

  const selectRow = (id) => {
    setCount(count + 1);
    rows.map((row, index) => {
      if (row.id === id) {
        setSelected([...row.deck]);
        const x = sortCards(deck, selectedCards);
        console.log('sortedCards', x);
        newDeck = rearrangeCards(rows, id);
        setDeck(newDeck);
      }
    });
  };

显示组件,其中定义了我的功能

import React, { useState } from 'react';
import Row from './Row';

import { generateRows, rearrangeCards, shuffle, sortCards, filterCards } from '../helpers';


function Display({ displayDeck }) {

  const [selectedCards, setSelected] = useState([]);

  const [count, setCount] = useState(0);

  const [deck, setDeck] = useState(displayDeck);

  const rows = generateRows(deck);

  let newDeck;

  const selectRow = (id) => {
    setCount(count + 1);
    rows.map((row, index) => {
      if (row.id === id) {
        setSelected([...row.deck]);
        const x = sortCards(deck, selectedCards);
        console.log('sortedCards', x);
        newDeck = rearrangeCards(rows, id);
        setDeck(newDeck);
      }
    });
  };

  if (count < 3) {
    return (
      <div>
        {
          rows.map((row, index) => {
            console.log(row.deck);
            return (<Row rowDeck={row.deck} selectRow={selectRow} rowId={row.id} key={index} />);
          })
        }
      </div>
    );
  }
  return (
    <div>
      <p>That is your card!</p>
      <img
        width="100"
        alt={`card: ${deck[10].value}-${deck[10].suit}`}
        src={deck[10].image}
        className="image"
      />
    </div>
  );
}


export default Display;

行组件,调用该函数的按钮为

import React from 'react';


function Row({ rowDeck, selectRow, rowId }) {
  function handleClick() {
    selectRow(rowId);
  }

  return (
    <div className="rowContainer">
      <button type="button" id="card" onClick={handleClick} className="rowButton">Shuffle</button>
      {
        rowDeck.map((card, index) => (
          <img
            key={index}
            width="100"
            alt={`card: ${card.value}-${card.suit}`}
            src={card.image}
            className="image"
          />
        ))
      }
    </div>
  );
}

export default Row;

1 个答案:

答案 0 :(得分:1)

setState是一个异步函数。 您正在尝试在设置状态后立即使用状态。

setSelected([...row.deck]);
const x = sortCards(deck, selectedCards);

还有它的旧价值。

您可以使用useEffect达到所需的效果。

useEffect(() => {
    const x = sortCards(deck, selectedCards);
    newDeck = rearrangeCards(rows, id);
    setDeck(newDeck);
  },[selectedCards]);