【问题标题】:index.js:1375 Warning: Each child in a list should have a unique "key" propindex.js:1375 警告:列表中的每个孩子都应该有一个唯一的“关键”道具
【发布时间】:2021-05-31 12:20:45
【问题描述】:

我写了一个 BlackJack 游戏,但是在我从扑克牌 API 查询 API 后,这些牌从未显示在屏幕上。我已经在控制台记录了玩家牌组和发牌牌组,它有卡牌数据,但没有显示任何内容。

这是错误: index.js:1375 警告:列表中的每个孩子都应该有一个唯一的“key”属性。

检查BlackJack的渲染方法。请参阅https://reactjs.org/link/warning-keys 了解更多信息。 在 div 在二十一点 (http://localhost:3000/static/js/main.chunk.js:4166:3) 在 WithStyles(BlackJack) (http://localhost:3000/static/js/0.chunk.js:54861:31)

这是查询后的数据

[Array(2)]
0: Array(2)
0: {code: "6C", image: "https://deckofcardsapi.com/static/img/6C.png", images: {…}, value: "6", suit: "CLUBS"}
1: {code: "JD", image: "https://deckofcardsapi.com/static/img/JD.png", images: {…}, value: "JACK", suit: "DIAMONDS"}
length: 2
__proto__: Array(0)
length: 1
__proto__: Array(0)

[Array(1)]
0: Array(1)
0: {code: "4H", image: "https://deckofcardsapi.com/static/img/4H.png", images: {…}, value: "4", suit: "HEARTS"}
length: 1
__proto__: Array(0)
length: 1
__proto__: Array(0)

下面是我的代码:

import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';
import { withStyles } from '@material-ui/core/styles';

const styles = () => ({
  app: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'column'
  },
  deckContainer: {
    textAlign: 'center'
  }
})

const BlackJack = ({ classes }) => {
  const [deckId, setDeckId] = useState(null);
  const [playerDeck, setPlayerDeck] = useState([]);
  const [dealerDeck, setDealerDeck] = useState([]);
  const [gameOver, setGameOver] = useState(false);
  const [winner, setWinner] = useState(null);

  useEffect(async () => {
    const deck_id = await axios.get('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1')
      .then(res => res.data.deck_id);
    setDeckId(deck_id);
  }, []);

  const handleStartGame = async () => {

    const playerDeckList = [];
    const dealerDeckList = [];
    const playerDrawnCards = await axios.get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=2`).then(res => res.data.cards);
    playerDeckList.push(playerDrawnCards);
    setPlayerDeck(playerDeckList);

    const dealerDrawnCards = await axios.get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`).then(res => res.data.cards);
    dealerDeckList.push(dealerDrawnCards);
    setDealerDeck(dealerDeckList);
  };
  console.log(deckId);
  console.log(playerDeck);
  console.log(dealerDeck);
  // console.log(playerDeck[0]);


  return (
    <div className={classes.app}>
      <h1>Welcome to the Black Jack Game</h1>
      <br />
      <div>
        <button onClick={handleStartGame}>start game</button>
        {/* <button onClick={handlePlayerHit}>hit</button> */}
        {/* <button onClick={handlePlayerStand}>stand</button> */}
        {/* <button onClick={handlePlayerReset}>reset game</button> */}
      </div>
      <div>
        {/* <GameOver isGameOver={gameOver} /> */}
      </div>
      <br />
      <div>
        <h2>Dealer: </h2>
        <div className={classes.deckContainer}>
          {dealerDeck.map(card => {
            return (
              <div key={card.code}>
                <img
                  src={card.image}
                  alt={card.value}
                />
              </div>
            )
          })}
        </div>
        <br />
        <h2>Player: </h2>
        <div className={classes.deckContainer}>
          {playerDeck.map(card => {
            return (
              <div key={card.code}>
                <img
                  src={card.image}
                  alt={card.value}
                />
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
};

export default withStyles(styles)(BlackJack);

【问题讨论】:

    标签: javascript reactjs key


    【解决方案1】:

    你设置的数据是数组中的一个数组,因为res.data.cards已经是一个数组了。

    所以把你的handleStartGame改成

      const handleStartGame = async () => {
        const playerDrawnCards = await axios
          .get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=2`)
          .then((res) => res.data.cards);
        setPlayerDeck(playerDrawnCards);
    
        const dealerDrawnCards = await axios
          .get(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`)
          .then((res) => res.data.cards);
        setDealerDeck(dealerDrawnCards);
      };
    

    【讨论】:

      【解决方案2】:

      这可能是因为获取 api 是异步操作。 React 首先渲染您的 jsx,然后执行逻辑,此时您的交易平台被映射为空。尝试为获取 api 设置另外 1 个状态(默认为 false),当 fetch 结束时将其设置为 false,然后在您的 JSX 中仅在 isFetching === false 时呈现相关组件。

      [isFetching, setIsFetching] = useState(true);
      .
      .
      .
      const handleStartGame = async ()=>{
      .
      .
      .
            setIsFetching(false);
         }
      .
      .
      .
      return(
          {!isFetching && dealerDeck.map... }
      )```
      

      【讨论】:

        猜你喜欢
        • 2019-08-04
        • 2021-01-12
        • 2022-06-28
        • 2023-02-17
        • 2021-07-20
        • 2019-12-05
        • 2021-09-05
        • 2020-03-01
        • 1970-01-01
        相关资源
        最近更新 更多