当我按下按钮'&#60'或'&#62'(增加或降低难度级别)时,在PureComponent(react.development)上收到错误消息“未捕获的TypeError:无法设置未定义的属性'props'”。 js:444)
我该如何解决?
上面的代码比实际的代码少得多,但是即使在这种大小下,它也不能很好地工作。
甚至“ blah-blah”也不会出现在控制台中。
StartMenu.js
import React from 'react';
import { connect } from 'react-redux';
import increaseDifficultyLevelfunction from './increaseDifficulyLevel';
import decreaseDifficultyLevelfunction from './decreaseDifficulyLevel';
function StartMenu(props) {
return (
<div className="start-menu-container">
<button
type="button"
id="leveldown"
onClick={decreaseDifficultyLevelfunction}
>
<
</button>
<div id="level">{props.difficultyLevel}</div>
<button
type="button"
id="levelup"
onClick={increaseDifficultyLevelfunction}
>
>
</button>
<button
type="button"
id="startButton"
onClick={props.restartGame}
>
start the game
</button>
</div>
);
}
const mapStateToProps = state => ({
difficultyLevel: state.difficultyLevel,
});
const mapDispatchToProps = dispatch => ({
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(StartMenu);
decreaseDifficultyLevel.js
import { connect } from 'react-redux';
import { decreaseDifficultyLevel } from '../../actions/actionCeator';
function decreaseDifficultyLevelfunction(props) {
console.log('blah-blah');
props.decreaseDifficultyLevel();
}
const mapStateToProps = state => ({
difficultyLevel: state.difficultyLevel,
});
const mapDispatchToProps = dispatch => ({
decreaseDifficultyLevel: () => { dispatch(decreaseDifficultyLevel()); },
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(decreaseDifficultyLevelfunction);
答案 0 :(得分:0)
我在这里仔细研究细节,决定尝试在codesandbox中进行尝试。
常见的React组件(直到挂钩)的情况是由类组件组成的。在这些情况下,函数/动作在顶层绑定,并将其上下文保留在子组件中(因此我们可以使用它们)。在功能组件中,情况有所不同。为了使操作生效,您需要执行以下操作:
Import * as actions from ’./actions’;
const mapDispatchToProps = dispatch => {
return {
actions: bindActionCreators(levelActions, dispatch)
};
};
为了执行步骤2,您需要在功能组件中声明功能(通常称为类变量),然后在按钮onClick属性中使用它们。像这样:
const {
increaseDifficultyLevelFunction,
decreaseDifficultyLevelFunction
} = props.actions;
const increaseLevel = () => increaseDifficultyLevelFunction();
const decreaseLevel = () => decreaseDifficultyLevelFunction();
选中此reference,它用示例覆盖了您的案例。