【问题标题】:Embedded Child Component in React is UndefinedReact 中的嵌入式子组件未定义
【发布时间】:2018-01-31 23:24:14
【问题描述】:

我有以下父组件:

import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
import _ from "lodash";

import  ChildComponent from "./ChildComponent";

class ParentComponent extends Component {
      constructor(props) {
        super(props);
        this.state = { 
        };

  }

  render() {
    return (
      <div>
      I'm at Parent
       <ChildComponent/>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {    }
 }


export default connect(mapStateToProps, null)(ParentComponent);

在父级内部有一个名为 ChildComponent 的组件,如下所示:

import React, { Component, PropTypes } from "react";
import { connect } from "react-redux";
import { reduxForm } from "redux-form";
import { bindActionCreators } from "redux";

class ChildComponent extends Component {
  constructor(props) {
    super(props);
  }
  componentWillMount() {
  }
  render() {
    return (
      <div>
      at the child
      </div>
    );
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {      
    },
    dispatch
  );
}

function mapStateToProps(state) {
  return {
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(
  ChildComponent
); 

当我尝试添加子组件时,我不断收到此错误:

但如果我点击继续,页面会恢复正常。我不明白子组件是如何未定义的。它只是嵌入的,不包含任何道具。

更新: 我不再收到错误消息,但我注意到当我打开这个特定组件时我的页面变为空白。我会做更多的故障排除。

【问题讨论】:

  • export default connect(mapStateToProps, mapDispatchToProps)( ChildComponent ); 更改为export default ChildComponent,看看问题是否仍然存在。此外,在简单的 repo、fiddle、codepen 或 codesandbox 中重现问题会更容易,因此我们可以轻松调试它。

标签: reactjs components parent


【解决方案1】:

我试用了您的代码,它对我来说很好用。我的想法可能是你的入口文件是什么样的?还是文件结构?如果你喜欢,你可以尝试下面的父子语法——它也可以这样工作:

孩子:

const mapStateToProps = () => {
  return {}
}

const ConnectedChildComponent = connect(
  mapStateToProps,
  {})(ChildComponent)

export default ConnectedChildComponent;

家长:

const mapStateToProps = () => {
  return {}
}

const ConnectedParentComponent = connect(
  mapStateToProps,
  {})(ParentComponent)

export default ConnectedParentComponent;

【讨论】:

  • 我试过了,结果是一样的。谢谢你的建议!
【解决方案2】:

在您的 ParentComponent 更改中:

import  ChildComponent from "./ChildComponent";

import  ChildComponent from "./ChildComponent.jsx";

即添加缺少的“.jsx”扩展名。默认情况下,您的代码很可能将导入确定为“.js”文件,而实际上它是“.jsx”文件。

【讨论】:

  • 有趣,我的文件都是 .js,所以可能是别的东西
  • 我之前遇到过像你一样的问题,对我来说这是因为我的 WebPack 设置需要能够区分 js 和 jsx 文件。
  • 我明白了。我对我的包进行了全新的 npm 安装,弹出错误似乎已经消失,但我的页面几秒钟后变为空白。我想我会继续调试,直到它再次弹出。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 2017-09-01
  • 1970-01-01
  • 2021-12-12
  • 2021-07-31
相关资源
最近更新 更多