首页 > 解决方案 > 为什么这个 React 状态返回为未定义?

问题描述

我的 React 组件中出现以下错误:

Failed to compile.

./src/components/GameInfo.js
Line 13:  'isPlaying' is not defined  no-undef

Search for the keywords to learn more about each error.

但是我在同一个文件中定义了那个状态,这是整个事情:

import React from 'react';
import { Layer, Stage } from 'react-konva';
import { connect } from 'react-redux';
import Banner from './Banner.js';
import CurrentTetromino from '../containers/CurrentTetromino.js';
import ActiveTetrominos from '../containers/ActiveTetrominos.js';
import gameConstants from '../gameConstants.js';
import style from '../styles/styles.css';

const { fieldHeight, fieldWidth } = gameConstants;

let GameField = ({ isPlaying, isPaused, isGameOver }) => {
if (isPlaying) {
    return (
        <div style={{display: 'inline'}}>
            <div className={style.gameField}>
                <Stage width={fieldWidth} height={fieldHeight}>
                    <Layer>
                        <CurrentTetromino />
                        <ActiveTetrominos />
                    </Layer>
                </Stage>
                { isPaused ? <Banner label="PAUSED" color="black" opacity=".5" /> : null}
            </div>
            { isGameOver ? <Banner label="GAME OVER" color="red" opacity=".8" /> : null}
        </div>
    );
}
return null;
};

const mapStateToProps = ({ gameStatus }) => ({
isPlaying: gameStatus !== 'IDLE',
isPaused: gameStatus === 'PAUSED',
isGameOver: gameStatus === 'GAME_OVER',
});

GameField = connect(mapStateToProps)(GameField);

export default GameField;

我想导致这种情况的错误也会同样返回 isPaused 和 isGameOver。

我不确定为什么它没有在 mapStateToProps 中拾取这些 const。不幸的是,对于 React,它实际上只告诉我发生错误的行(第 13 行)。

任何建议将不胜感激。

标签: reactjs

解决方案


这个愚蠢的网站不允许我发表评论,但我会检查你的 mSTP 中的 gameStatus 是否正常。我不会进行隐式返回,而是将其显式更改并 console.log 在您的 mSTP 中记录 gameStatus。或者在那里打一个调试器。这将是我检查的第一直觉。

const mapStateToProps = ({ gameStatus }) => {
   console.log(gameStatus);
   return { 
      isPlaying: gameStatus !== 'IDLE',
      ....
   }
}

如果你能分享这带来了什么,我可能会帮助你更多。否则祝你好运,希望这有助于解决这个问题。


推荐阅读