javascript - React Context 和单独的类

标签 javascript reactjs

我已经放弃了让 mt 了解 Redux 的希望(我是 React 的新手),并且看到 React 的 Alpha 版本提供了一个新的 Context。

所以我正在尝试学习它,我的目标是,我有一个导航栏,我想在我的上下文中响应一个状态,{isAuthorised: false}

我正在关注 this guys video :

但他将所有代码都放在一个文件中。我正努力做到“正确”。

我所做的是创建一个名为“context”的文件夹,并在其中创建一个名为 provider.jsx 的 jsx。

import React, {Component} from 'react';


export default class MyProvider extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isAuthenticated: false
        }
    }

    render() {
        const MyContext = React.createContext();
        return(
            <MyContext.Provider value="Test Text">
                {this.props.children}
            </MyContext.Provider>
        )
    }
}

https://github.com/CraigInBrisbane/ReactLearning/blob/master/src/context/provider.jsx

在那里,我在渲染中创建了上下文(这可能是错误的......也许这意味着在我的 App jsx 中发生?)。

我在那里创建了一个状态,默认 isAuthenticated 为 false。 (稍后我将添加代码以将其设置为应有的值)。

这会编译...并运行。

在我的 App 组件中,我这样使用我的提供者:

import MyProvider from './context/provider.jsx';


export default class App extends Component {

    render() {
        return (
            <MyProvider>
            <div>
                <Router>
                    <div>
                    <Navbar />
                        <Route exact path='/' component={Home}  />
                        <Route path='/about' component={About} />

https://github.com/CraigInBrisbane/ReactLearning/blob/master/src/app.jsx

所以我用 MyProvider 包装我的所有代码。

在我的 Navbar 组件中,我导入了我的提供者:

import MyProvider from '../../context/provider.jsx';

然后我尝试在我的渲染中从我的提供者输出一些东西:

     return (
    <div>
         <MyProvider.Consumer>
            {(context)=> (
                <p>Here I am {context}</p>
            )}
        </MyProvider.Consumer> 
    <nav className="navbar navbar-expand">

https://github.com/CraigInBrisbane/ReactLearning/blob/master/src/components/navbar/navbar.jsx

但这对我来说非常糟糕。

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of Navbar. in Navbar (created by App) in div (created by App)

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

我怎样才能让它发挥作用?我的 .createContext 应该放在哪里?

Code (With error) is here .

最佳答案

所以问题是您导出 MyProvider 并尝试访问其上的静态组件 - 这是 undefined:

console.log(MyProvider.Consumer);  // undefined

Consumer 作为静态属性存在于MyContext 组件中。

您需要更改的内容:

provider.jsx

import React, {Component} from 'react';

export const MyContext = React.createContext();

export default class MyProvider extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isAuthenticated: false
        }
    }

    render() {

        return(
            <MyContext.Provider value={this.state.isAuthenticated}>
                {this.props.children}
            </MyContext.Provider>
        )
    }
}

然后在 navbar.jsx

import MyProvider, { MyContext } from '../../context/provider.jsx';

<MyProvider>
   <MyContext.Consumer>
      {(context)=> (
          <p>Here I am {context}</p>
      )}
   </MyContext.Consumer> 
</MyProvider>

看看this tutorial .

编辑:

要让 Consumer 存在于 MyProvider 中,您必须在其上分配指向 MyContext Consumer

的静态变量
MyProvider.Consumer = MyContext.Consumer;

然后我想你可以像这样使用它:

<MyProvider>
   <MyProvider.Consumer>
      {(context)=> (
          <p>Here I am {context}</p>
      )}
   </MyProvider.Consumer> 
</MyProvider>

但是我不确定这是否是个好主意。

关于javascript - React Context 和单独的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49474425/

相关文章:

javascript - 不变违规 : Calling pop to route for a route that doesn't exist

javascript - 通过javascript在新窗口中查看pdf文件

php - 从 JavaScript 调用带参数的函数

javascript - 如何停止获取 __webpack_hmr

javascript - 我试图让 Canvas 元素随着键盘移动

javascript - 删除具有特定索引的 select2 标签?

javascript - 删除发生在打开模式之前并确认删除

javascript - React类组件中Context的调用函数

javascript - Material -UI FAB 悬停颜色

reactjs - getDerivedStateFromError() 中会出现什么错误类型?