【问题标题】:React Redux "Cannot read property 'props' of undefined"React Redux“无法读取未定义的属性'props'”
【发布时间】:2021-01-15 16:25:33
【问题描述】:

我对 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 中,我将 props 传递给接口组件:

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

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

getCurrentLocation = (event) =&gt; {...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 (
  (...)
)

感谢所有感兴趣的人。

【问题讨论】:

  • 你明白错误信息告诉你什么吗?
  • 不完全是,我的想法是:我可以像 return (
    {this.props.locations.sampleLocation
    ) 一样显示位置作为回报。它在组件中,但为什么不在此组件中的函数中,因为“this”指的是当前组件?在使用 Redux 之前它曾经可以工作
  • 据我了解,它没有接收道具,因为您没有接收到的构造函数。在构造函数中添加 super(props)。
  • @Przemek 它告诉你的是this 是未定义的。解决您的问题将涉及调查为什么会这样。我不认为它与redux有任何关系。这可能与您声明类和/或 babel 配置的方式有关。
  • 我建议在 Code Sandbox 上发布一个小副本。

标签: reactjs redux react-props


【解决方案1】:

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

constructor(props) {
        super(props);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-10
    • 2019-02-15
    • 1970-01-01
    • 2017-06-22
    • 2017-09-05
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多