reactjs - 为什么这个 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 行)。
任何建议将不胜感激。
解决方案
这个愚蠢的网站不允许我发表评论,但我会检查你的 mSTP 中的 gameStatus 是否正常。我不会进行隐式返回,而是将其显式更改并 console.log 在您的 mSTP 中记录 gameStatus。或者在那里打一个调试器。这将是我检查的第一直觉。
const mapStateToProps = ({ gameStatus }) => {
console.log(gameStatus);
return {
isPlaying: gameStatus !== 'IDLE',
....
}
}
如果你能分享这带来了什么,我可能会帮助你更多。否则祝你好运,希望这有助于解决这个问题。
推荐阅读
- java - 如何在 Flux.subscribe 之后收集数据以将其作为 json 数组发送?
- javascript - Moment.js - 从输入表单创建“时间”唯一变量
- angularjs - 在 NG-Repeat 中将 html 添加到 json 内容
- sql - SQL如何获取项目列表并根据日期字段创建新表
- java - Java:包含和添加?
- amazon-s3 - 尝试将对象放入 S3 存储桶时访问被拒绝
- swift - 在 Swift 结构中的常量上使用 static 的目的是什么?
- c - 使用子层修改C API数组访问?
- awk - 用 sed 或 awk 替换字符串,它标识如下所述的模式
- asp.net-core - 不同的会话超时.net核心会话