【问题标题】:React.createElement: type is invalid -- expected a string (for built-in components) or a class/functionReact.createElement:类型无效——需要一个字符串(对于内置组件)或一个类/函数
【发布时间】:2017-11-29 08:16:01
【问题描述】:

当我尝试导入组件时,我从 react 中得到了这个神秘的错误。我收到的错误消息如下。不知道如何调试这个,感谢任何帮助。

未捕获的错误:元素类型无效:应为字符串(对于 内置组件)或类/函数(用于复合组件) 但得到:未定义。您可能忘记从 定义它的文件。检查App的渲染方法。

--- 我的 index.jsx

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import reducer from './reducers/reducer'

let store = createStore(reducer)

import App from './components/App'

ReactDOM.render(<App store={store}/>, document.getElementById('app')); 

-- 我的应用

import React, { Component } from 'react'
import { incrementCount } from '../actions/actionsOne'
import  CountWidgetContainer   from '../containers/CountWidgetContainer'

export default class App extends Component {

  render(){
    return (
      <div>
       <CountWidgetContainer store={this.props.store} />
      </div>
    )
  }
}

-- 容器组件

import React, { Component } from 'react'
import { INCREMENT_COUNTER } from '../actions/actionsOne'
import  CountWidget  from '../Components/CountWidget'

export default class CountWidgetContainer extends Component {

    constructor(props) {
     super(props)
      this.state = {
       count: props.store.getState()
      };
     this.handleChange = this.handleChange.bind(this);
     this.handleClick = this.handleClick.bind(this);
    }

   componentDidMount() {
      this.props.store.subscribe(this.handleChange)
   }

   handleChange() {
      this.setState({
        count: this.props.store.getState()
      })
   }

  handleClick() {
   let action = incrementCount()
    this.props.store.dispatch(action)
    console.log('action: ', action);
  }

  render() {
      return (
        <CountWidget count={this.state.count} handleClick={this.state.handleClick} />
      ) 
  }
}

【问题讨论】:

  • 附带说明,您可以尝试MobX 而不是 Redux。你可能会喜欢它
  • 我正在考虑回滚编辑,因为您已经删除了一个明显的错误,该错误会使问题重复。错误信息还是一样吗?

标签: reactjs


【解决方案1】:

import { CountWidgetContainer } from '../containers/CountWidgetContainer'

在这个组件中你使用export default所以,你不需要使用花括号。

import CountWidgetContainer from '../containers/CountWidgetContainer';

并检查组件CountWidget 导出,如果它是默认的你也不应该在Container 中使用花括号。

【讨论】:

  • 我也是这么想的。当我删除花括号时,它仍然有同样的错误
  • CountWidget 导出和导入呢?
  • @Jimi 你使用的是redux,所以你需要使用connect,你不需要将store传递给props中的每个组件。查看更多详细信息:redux.js.org/docs/basics/…
  • @Andrew,我也删除了这些。我仍然得到同样的错误。似乎很难调试。
  • @MayankShukla,我是新手,欢迎提出建议。
猜你喜欢
  • 2018-08-02
  • 2020-09-04
  • 2021-11-17
  • 1970-01-01
  • 2018-01-18
  • 2017-08-06
  • 2022-01-25
  • 2017-08-30
  • 2019-11-27
相关资源
最近更新 更多