我正在尝试在我的 React 项目中使用 redux,但在使用“react-redux”中的“connect()”方法时遇到问题。
我创建了我需要的商店和 reducer ,但是当我尝试连接我的组件时,没有任何显示,它给我错误。
当我尝试连接我的组件 App 时:
import React from "react";
import PrivateRoute from "react-private-route";
import { connect } from "react-redux";
import { Router, Route, Switch } from "react-router-dom";
import { createBrowserHistory } from "history";
import { Auth } from "aws-amplify";
import indexRoutes from "routes/index";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (<Router>[...]</Router>);
}
}
function mapStateToProps(state) {
console.log(state);
return {
myInfo: state
};
}
const mapDispatchToProps = dispatch => {
return {
test: () => dispatch({ type: "TEST", payload: {} })
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
我得到错误:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
最佳答案
如评论中所述,解决方案是将您的应用包装在 <Provider></Provider>
中,这使得商店可用于使用 connect()
的嵌套组件.如果你使用的是 react router v4,你还应该使用 <ConnectedRouter>
而不是简单的路由器。
可以在 their Github docs 中找到一个很好的工作示例
import { ConnectedRouter } from 'connected-react-router'
import { Provider } from 'react-redux'
<Provider store={store}>
<ConnectedRouter history={history}> { }
...
</ConnectedRouter>
</Provider>
https://stackoverflow.com/questions/55691306/
相关文章:
kubernetes - 如何将 kubernetes pods 标签添加到普罗米修斯指标?
python-3.x - Python3 requests.get 太慢
react-native - 错误无法构建 iOS 项目。我们运行了 "xcodebuild"命令,
html - 在 <input> 上使用 onChange 时未注册空间
git - 如何修复 git bash 错误异常 : STATUS_ACCESS_VIOLATION
php - Composer 更新给出错误说插件无法初始化,找不到每个包的类
laravel - 登录 laravel 背包后有条件地重定向用户