错误:元素类型无效:预期为字符串(对于内置组件)或类/函数

时间:2018-09-11 22:05:33

标签: html css json reactjs redux

https://stackblitz.com/edit/react-redux-realworld-j95tpu?file=actions/index.js

code
export function fetchPosts(channel) {
  return function (dispatch) {
    dispatch(requestPosts());
    return fetch(`https://newsapi.org/v1/articles?source=${channel}&apiKey=${MY_API_KEY}`)
      .then(response => response.json(),
      error => console.log('An error occurred.', error),
    )
      .then((json) => {
        dispatch(receivedPosts(json));
      }, );
  };
}

error

VM1672:37 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `TopNews`.
    in TopNews (created by Connect(TopNews))
    in Connect(TopNews) (created by App)
    in div (created by App)
    in App
    in Provider


Uncaught (in promise) Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `TopNews`.
    at invariant (invariant.js:42)
    at instantiateReactComponent (instantiateReactComponent.js:74)
    at instantiateChild (ReactChildReconciler.js:44)
    at eval (ReactChildReconciler.js:71)
    at traverseAllChildrenImpl (traverseAllChildren.js:77)
    at traverseAllChildren (traverseAllChildren.js:172)
    at Object.instantiateChildren (ReactChildReconciler.js:70)
    at ReactDOMComponent._reconcilerInstantiateChildren (ReactMultiChild.js:185)
    at ReactDOMComponent.mountChildren (ReactMultiChild.js:224)
    at ReactDOMComponent._createInitialChildren (ReactDOMComponent.js:703)

1 个答案:

答案 0 :(得分:1)

实际的问题是导入/导出语法问题。我将指导您如何找到它。

问题的实际位置由组件堆栈跟踪显示:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `TopNews`.
    in TopNews (created by Connect(TopNews))
    in Connect(TopNews) (created by App)
    in div (created by App)
    in App
    in Provider

如果我们查看TopNews.js,它将仅呈现<h3><div><NewsItem>h3div只是基本标记,所以可能是问题NewsItem

TopNews.js的顶部,您拥有:

import { NewsItem } from '../components/NewsItem';

但是,在NewsItem.js中,您具有:

export default NewsItem ;

因此,您正在执行默认导出,但是执行了命名导入,因此NewsItemTopNews.js中未定义。

尝试将其更改为import NewsItem from "../components/NewsItem",它应该可以工作。