我正在尝试学习React Redux API调用
所以我举了一个例子,并在stackblitz中实现,但是当我选择某些频道并点击热门新闻按钮时,出现以下错误
你能告诉我如何解决吗
在下面提供我的代码和stackblitz
https://medium.com/@lavitr01051977/basic-react-redux-app-with-async-call-to-api-e478e6e0c48b
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)
最佳答案
实际的问题是导入/导出语法问题。我将指导您如何找到它。
问题的实际位置由组件堆栈跟踪显示:
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>
。 h3
和div
只是基本标记,因此可能是NewsItem
造成的。在
TopNews.js
的顶部,您具有:import { NewsItem } from '../components/NewsItem';
但是,在
NewsItem.js
中,您具有:export default NewsItem ;
因此,您正在执行默认导出,但是执行了命名导入,因此在
NewsItem
中未定义TopNews.js
。尝试将其更改为
import NewsItem from "../components/NewsItem"
,它应该可以工作。