【问题标题】:React and Redux: Getting is not defined no-undef errorReact 和 Redux:Getting is not defined no-undef 错误
【发布时间】:2021-02-18 19:14:52
【问题描述】:

我不知道为什么我不断收到以下错误:'isAuthenticated' is not defined 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);

【问题讨论】:

  • 您正在混合功能和类组件语法。函数式组件没有渲染功能,它们渲染功能。你只需返回 JSX
  • 对不起,我还在学习。你能给我举个例子吗?

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


【解决方案1】:

isAuthenticated 将作为组件 props 传递,您需要从组件 props 中获取它,并且您必须在父组件中定义提供程序。

试试下面的代码。

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中的指南。

【讨论】:

  • 我收到以下错误:错误:在“Connect(App)”的上下文中找不到“store”。要么将根组件包装在 中,要么将自定义 React 上下文提供者传递给 ,并将相应的 React 上下文使用者传递给连接选项中的 Connect(App)。
  • @tim_woods 提供者 inside 您的 App 组件,因此您将无法连接 App 组件本身。您连接的任何内容都需要呈现为提供者的子节点
  • @Jayce444 感谢您的回复。我按照您的建议通过添加 render() 更新了上面的代码,但出现以下错误:解析错误:意外的令牌,预期的“;”。错误指向其 render() 所在的行
  • 功能组件中没有使用Render,意思是说App组件应该是provider组件的子组件。
  • 我已经添加了index.js的代码,请相应调整存储路径
猜你喜欢
  • 2017-03-20
  • 2021-12-06
  • 1970-01-01
  • 2021-05-25
  • 2019-04-04
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 2020-11-07
相关资源
最近更新 更多