我是Redux的新手。我已经成功实现了<Provider store={store}>
,但是,当我尝试在App.js
中使用它来控制私有路由时,出现了以下错误,并且不确定它试图告诉我什么去做。感谢帮助。
“× 错误:在“ Connect(App)”的上下文中找不到“商店”。要么将根组件包装在中,要么将自定义React上下文提供程序传递给,然后传递相应的React”
class App extends Component {
componentDidMount() {
store.dispatch(loadUser());
}
static propTypes = {
auth: PropTypes.object.isRequired
};
render() {
const { isAuthenticated } = this.props.auth;
return (
<Provider store={store}>
<Router>
<Header />
<Switch>
<Route exact path="/login">
<ErrorBoundary>
<LoginPage />
</ErrorBoundary>
</Route>
<PrivateRoute path="/purchase_order">
<PurchaseOrderPage />
</PrivateRoute>
</Switch>
</Router>
</Provider>
);
}
}
const fakeAuth = {
isAuthenticated: true,
authenticate(cb) {
fakeAuth.isAuthenticated = true;
setTimeout(cb, 100); // fake async
},
signout(cb) {
fakeAuth.isAuthenticated = false;
setTimeout(cb, 100);
}
};
function PrivateRoute({ children, ...rest }) {
return (
<Route
{...rest}
render={({ location }) =>
console.log(' fakeAuth.isAuthenticated', fakeAuth.isAuthenticated) ||
fakeAuth.isAuthenticated ? (
children
) : (
<Redirect
to={{
pathname: '/login',
state: {
from: location
}
}}
/>
)
}
/>
);
}
const mapStateToProps = (state) => ({
auth: state.auth
});
export default connect(mapStateToProps, null)(App);