首页 > 解决方案 > React Redux“无法读取未定义的属性'props'”

问题描述

我对 React 很陌生,我创建了一个简单的游戏。我现在决定重建它并开始使用 Redux。我用

{React.cloneElement(this.props.children, this.props)} in `Main.js`  

将道具传递给 World.js 的第一个孩子:

 Main.js
    (...)
    {React.cloneElement(this.props.children, this.props)} //props passed to World
    (...)
 export default Main;

然后在 World.js 中,我将道具传递给接口组件:

World.js
   (...)
     <Interface
        {...this.props}
        /> 
   (...) 
export default World;

最后,Interface.js问题出在哪里。在getCurrentLocation功能上,我试图达到locations它是组件道具之一。它可作为组件的道具使用,但在功能中显示“无法读取未定义的属性'道具'”。另一件事是我不得不从

getCurrentLocation = (event) => {...为了getCurrentLocation (event) {...让它工作

Interface.js

class Interface extends React.Component {

    getCurrentLocation  (event)  { // Why is getCurrentLocation = (event) => ... not working?
      
        event.currentTarget.classList.add('active');
        const locationName = event.currentTarget.dataset.name;
    
        const updatedLocation={
            ...this.props.locations[locationName], //Line with error: Cannot read property 'props' of undefined
            isCurrentLocation: true,
        }
        (...)
         }
       };

render() {
 
return (
  (...)
)

感谢所有感兴趣的人。

标签: reactjsreduxreact-props

解决方案


像这样添加构造函数解决了这个问题

constructor(props) {
        super(props);

        this.getCurrentLocation = this.getCurrentLocation.bind(this);
        this.setCurrentLocation = this.props.setCurrentLocation.bind(this);
      }

推荐阅读