我不知道为什么我一直收到以下错误:"isAuthenticated"没有定义也没有定义。我从mapStateToProps中获取它,然后在我的switch标签中调用它。任何帮助都将不胜感激。非常感谢。
//App.js文件
const App = () => {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<Provider store={store}>
<div className="App">
<Router>
<Switch>
<Route exact path="/" component={LandingPage} />
{!isAuthenticated ? <Route exact path="/login" component={LoginPage} /> : <ProtectedRoute exact path="/userfeed" component={UserFeed} />}
</Switch>
</Router>
</div>
</Provider>
);
}
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps)(App);
isAuthenticated
将作为组件道具传递,您需要从组件道具中获取它,并且必须在父组件中定义提供者。
请尝试以下代码。
const App = ({ isAuthenticated }) => {
useEffect(() => {
store.dispatch(loadUser());
}, [])
return (
<div className="App">
<Router>
<Switch>
<Route exact path="/" component={LandingPage} />
{!isAuthenticated ? <Route exact path="/login" component={LoginPage} /> : <ProtectedRoute exact path="/userfeed" component={UserFeed} />}
</Switch>
</Router>
</div>
);
};
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps)(App);
index.js
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import App from './App'
import store from './store'
ReactDOM.render(
// Render a `<Provider>` around the entire `<App>`,
// and pass the Redux store to as a prop
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
)
有关详细信息,请阅读官方文档中的指南。