React和Redux:获取未定义no-undef错误

时间:2020-11-06 02:40:33

标签: javascript reactjs redux react-redux react-router

我不知道为什么总是出现以下错误:'isAuthenticated'未定义为no-undef。我从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);

1 个答案:

答案 0 :(得分:1)

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')
)

有关详细信息,请阅读官方文档here中的指南。