简体   繁体   English

尝试使用 Context API 时看到“render is not a function”

[英]Seeing "render is not a function" when trying to use Context API

I'm trying to learn the Context API, and what I want to achieve, is showing the Logged In user in my header, as well as manipulate my menu options based on the logged in state (Is it safe to store 'isAuthenticated' in state?)我正在尝试学习 Context API,我想要实现的是在我的标题中显示登录用户,以及根据登录状态操作我的菜单选项(将“isAuthenticated”存储在状态?)

My context class:我的上下文类:

import React from 'react';

const Context = React.createContext();

export class Provider extends React.Component {

    state = {
        isAuthenticated: true,
        user: {
            name: "Joe Smith",
            email: "joe.smith@here.com"
        }
    }

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

export const Consumer = Context.Consumer;

So, extremely basic.所以,非常基础。 Sets up a state, and in some child components later, I want to display the chaps name.设置一个状态,以后在一些子组件中,我想显示chaps名称。

My App.js is the using 'Provider', so that all my components have access to this data:我的 App.js 是 using 'Provider',所以我的所有组件都可以访问这些数据:

import React from 'react';
import { HashRouter , Route, Switch } from 'react-router-dom';
import Home from './components/home';
import Header from './components/header';
import Accounts from './components/accounts';
import Reports from './components/reports';
import Login from './components/login';
import {Container} from 'reactstrap';

import { Provider } from './context';

function App() {
  return (
    <div className="App">
      <Provider>
        <HashRouter>
          <Header />
          <Container>
            <Switch>
              <Route exact path="/" component={Home} />
              <Route exact path="/accounts" component={Accounts} />
              <Route exact path="/reports" component={Reports} />
              <Route exact path="/login" component={Login} />
            </Switch>
          </Container>
        </HashRouter>
      </Provider>
    </div>
  );
}

export default App;

So in this case, 'Header' needs access to my context.所以在这种情况下,'Header' 需要访问我的上下文。 My Header will show a menu (which, based on some info I'll add to the context, will show or hide options, login buttons etc).我的标题将显示一个菜单(根据我将添加到上下文中的一些信息,它将显示或隐藏选项、登录按钮等)。

Under the menu, I want to show a small info bar.在菜单下,我想显示一个小信息栏。 Logged in user name, for example.例如,登录用户名。 So, my header class looks like this:所以,我的头类看起来像这样:

import React from 'react';
import Menu from './menu';
import InfoBar from './infobar';
import { Consumer } from '../context';

class Header extends React.Component {

    render() {
        const menuStyle = {
            paddingBottom: "5px"
        }

        return(
            <Consumer>
                <div style={menuStyle}>
                    {value => {
                        console.log(value);
                        return (
                            <h1>Test</h1>
                        )
                    }}
                    <Menu  />
                    <InfoBar />
                </div>
            </Consumer>
        )
    }
}

export default Header;

But the problem now happens.但问题现在发生了。 When I run my code, it compiles and runs, but right away, I get a runtime error:当我运行我的代码时,它会编译并运行,但立即出现运行时错误:

TypeError: render is not a function updateContextConsumer C:/Storage/Scratch/ReactApp/accufinance/node_modules/react-dom/cjs/react-dom.development.js:16082类型错误:渲染不是函数 updateContextConsumer C:/Storage/Scratch/ReactApp/accufinance/node_modules/react-dom/cjs/react-dom.development.js:16082

I read something about returns and multiple children, but my code seems to not have that issue.我读了一些关于返回和多个孩子的内容,但我的代码似乎没有这个问题。 Any assistance with understanding the issue and where the problem is happening would be great.任何有助于理解问题和问题发生位置的帮助都会很棒。 If I comment out the code in 'header', no error... but... no screen either.如果我注释掉 'header' 中的代码,没有错误......但是......也没有屏幕。 It seems to be occuring in the area.它似乎正在该地区发生。

The Context Consumer uses a render prop, specifically a function as a child component, so it expects its immediate child to be a function (not a component). Context Consumer 使用一个 render prop,特别是一个函数作为子组件,所以它期望它的直接子组件是一个函数(而不是一个组件)。 In your case, you can just move the div inside the function:在您的情况下,您可以在函数内移动 div:

<Consumer>
  {value => {
    console.log(value);
    return (
      <div style={menuStyle}>
        <h1>Test</h1>
        <Menu />
        <InfoBar />     
      </div>
    )
  }}
</Consumer>

Render props are really powerful for when you want to expose a component's internal state to its children, but when you also want to use it with different types of children.当您想将组件的内部状态公开给它的子组件时,渲染道具非常强大,但当您还想将它用于不同类型的子组件时。

The pattern is like this:图案是这样的:

class Parent extends Component {
  state = { name: 'Mike' }

  handleChange = (e) => this.setState({ name: e.target.value })

  render() {
    // Here's the main difference: We expect `children` to be
    // a function, and we pass name in as the argument
    return children(state.name);
  }
}

const InputChild = props => <input value={props.name} />

const HeaderChild = props => <h1>{props.name}</h1>

const App = () => {
  return (
    <Parent>
      {name => {
        // We could easily swap in `HeaderChild` here (or
        // anything else!), passing `Parent`'s internal
        // state.name to it instead:
        <InputChild name={name} />
      }
    </Parent>
  )
}

This is what makes Context work, because the Consumer doesn't have any knowledge of the components in its children, but it can expose its state (which is the value from the Provider).这就是使 Context 工作的原因,因为消费者对其子级中的组件没有任何了解,但它可以公开其状态(这是来自 Provider 的值)。

The React docs have a great section on render props: https://reactjs.org/docs/render-props.html React 文档有一个关于渲染道具的很棒的部分: https : //reactjs.org/docs/render-props.html

如果您正在使用功能组件并将useContextcreateContext一起使用,您可能会忘记在渲染之前添加“Provider”,例如myContext.Provider在我的情况下,我通常忘记.Provider并只写<myContext></myContext>而我必须这样做这... <myContext.Provider></myContext.Provider>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 面临类型错误:使用上下文 API 时,渲染不是 function - Faced TypeError: render is not a function when using Context API TypeError: 渲染不是 function 上下文 Api 多个上下文 - TypeError: render is not a function Context Api Multiple Context 运行此代码上下文API和Reactjs时出现Render not Function错误 - Getting a Render not Function Error, when I run this Code Context API and Reactjs 从React Context API渲染功能中的地图功能渲染HTML - Rendering HTML from map function in React Context API render function React context api 仅呈现使用已更改值的组件 - React context api only render components that use values that have changed 路由器上下文在第二次使用时在路由器组件渲染功能中为空 - Router context is empty in Router Component render function on second use React Context:TypeError:render不是函数 - React Context: TypeError: render is not a function 在尝试运行Mocha测试时,require.context不是函数 - require.context not a function when trying to run Mocha tests TypeError:数字不是函数-尝试使用Google Maps API V3 DirectionsService时 - TypeError: Number is not a function - when trying to use Google Maps API V3 DirectionsService 看到元素时激活滚动功能 - scroll function activate when seeing element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM