【问题标题】:Redux `connect()` return an objectRedux `connect()` 返回一个对象
【发布时间】:2019-10-18 09:00:16
【问题描述】:

我正在使用这些库:

react: 16.8.6
redux: 4.0.1
react-redux: 7.0.3

我有一个简单的组件(Typescript):

import ...;  
import { connect } from 'react-redux';

class ExampleComponent extends React.PureComponent<IProps, {}> {
    constructor(props: any) {
        super(props);
    }

    public render() {
        return (
            <div>
                {this.props.name}
            </div>
        );
    }
}

interface IProps{
    name: string;
}

const mapStateToProps = (state) => {
    return {
        name: state.name
    };
}

export default connect(mapStateToProps)(ExampleComponent);

我有一个父组件:

import ExampleComponent from './ExampleComponent';

export default class App extends React.PureComponent<{}, {}> {
    constructor(props: any) {
        super(props);
    }

    public render() {
        return (
            <div>
                <ExampleComponent />
            </div>
        );
    }
}

由于某种原因,connect(mapStateToProps)(ExampleComponent) 返回一个对象而不是 React 组件。 我收到一个错误:

未捕获的错误:不变违规:元素类型无效:预期 一个字符串(用于内置组件)或一个类/函数,但得到:对象

当我尝试执行console.info(typeof connect(mapStateToProps)(ExampleComponent)) 时,它只会将object 打印到控制台。

我该如何解决这个问题?

【问题讨论】:

  • 使用connect(mapStateToProps, null)(ExampleComponent)
  • 它没有帮助。它仍然会引发错误。
  • 你是如何在文件中导入connect
  • import { connect } from 'react-redux';(我会在问题中添加这个)
  • connect()(Component) 应该返回一个组件。我怀疑该错误是在其他地方引起的。请在问题中包含完整的错误回溯。这种错误可能是由于某处导入时的拼写错误造成的。

标签: reactjs typescript react-redux


【解决方案1】:

我发现了问题。这是react-dom 库。它被错误地设置为16.4.XXredux-dom connect 使用React.memo() 可以返回对象的方法。 但是react-dom 16.4.XX 不知道如何处理这些对象。

升级到react-dom 16.8.XX 解决了这个问题。

【讨论】:

    【解决方案2】:

    乍一看,问题似乎出在 {this.props.name} 由于某种原因,它应该是一个字符串并获取一个对象。

    请尝试控制台'name'

    render() {
     const { name } = this.props
     console.log('name', name)
    
     return (
      //
     )
    }
    

    这很可能是问题所在。

    【讨论】:

    • 不,问题出在App 组件上。错误显示:Check the render method of "App"&lt;ExampleComponent /&gt; 似乎是一个对象而不是一个组件。
    猜你喜欢
    • 2019-07-26
    • 2018-02-23
    • 1970-01-01
    • 2017-08-18
    • 2022-10-08
    • 2015-06-06
    • 2015-06-03
    • 2014-05-27
    • 2014-05-22
    相关资源
    最近更新 更多