简单的授权检查会导致redux存储提供程序崩溃



我在React和Redux中构建了一个应用程序,它一直运行良好,直到我实现了一个简单的localStorage检查来呈现App或我称之为Gateway:的身份验证页面

App.js

import React, { useState } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./redux/store";
import NavBar from "./components/NavBar";
import Settings from "./views/Settings";
import Gateway from "./views/Gateway";
import Profile from "./views/Profile";
import Signup from "./views/Signup";
import NewTestimonialPage from "./views/NewTestimonialPage";
import NotFoundPage from "./views/NotFoundPage";
import "./styles/App.scss";
function App() {
// new additions start here...
const [loggedIn, setLoggedIn] = useState(
localStorage.getItem("loggedIn") === "true"
);
if (!loggedIn) {
return <Gateway />;
}
...and end here

return (
<Router>
<Provider store={store}>
<NavBar />
<div className="navbar-dodger"></div>
<div className="App">
<Switch>
<Route exact path="/" component={Gateway} />
<Route path="/signup" component={Signup} />
<Route path="/settings/:userId" component={Settings} />
<Route path="/profile/:userId" component={Profile} />
<Route
path="/new-testimonial/:userId"
component={NewTestimonialPage}
/>
<Route path="/404" component={NotFoundPage} />
<Route component={NotFoundPage} />
</Switch>
</div>
</Provider>
</Router>
);
}
export default App;

没有注释之间的代码,一切都是100%好的。

现在,我抛出这个错误:

Could not find "store" in the context of "Connect(EmailCheck)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(EmailCheck) in connect options.

如果我也在If块中呈现提供程序,它就会工作。为什么?如果我在Gateway中没有以任何方式使用redux,为什么我需要一个商店?

如果您在<Gateway>组件中使用redux,则您的组件必须封装在<Provider>

它应该看起来像:

return (
<Router>
<Provider store={store}>
{!loggedIn ?? <Gateway /> : <YourApplication />}
</Provider>
</Router>
);

为应用程序创建一个组件,如YourApplication.js:

return (
<>    
<NavBar />
<div className="navbar-dodger"></div>
<div className="App">
<Switch>
<Route exact path="/" component={Gateway} />
<Route path="/signup" component={Signup} />
<Route path="/settings/:userId" component={Settings} />
<Route path="/profile/:userId" component={Profile} />
<Route
path="/new-testimonial/:userId"
component={NewTestimonialPage}
/>
<Route path="/404" component={NotFoundPage} />
<Route component={NotFoundPage} />
</Switch>
</div>
<>
);

最新更新