我是新来的人,我正在尝试了解上下文。 因此,我尝试为用户创建提供者和使用者。 Ftm Im只是试图显示该值,但我稍后会将该值传递给路由器和其他组件。
这是提供者
const UserContext = React.createContext();
// Create an exportable consumer that can be injected into components
export const UserConsumer = UserContext.Consumer
// Create the provider using a traditional React.Component class
class UserProvider extends React.Component {
render() {
return (
// value prop is where we define what values
// that are accessible to consumer components
<UserContext.Provider value={{
username: 'Crunchy Crunch',
dateJoined: '9/1/18',
membershipLevel: 'Silver'
}}>
{this.props.children}
</UserContext.Provider>
)
}
}
这是应用程序:
class App extends React.Component {
render() {
return (
<UserProvider>
<Fragment>
<Router>
<Nav />
<UserConsumer>
{state => (
<p>Username: {state.username}</p>
)}
</UserConsumer>
<Switch>
<ProtectedRoute exact path="/profile" component={Profile} />
<Route exact path="/" component={Index} />
</Switch>
</Router>
</Fragment>
</UserProvider>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
我在终端中没有收到任何错误,但是我在浏览器中收到了以下消息:
函数作为React子代无效。如果您可能会发生这种情况 返回一个Component而不是从render返回。也许你 打算调用此函数而不是返回它。
这是什么错误,我基本没有正确执行某些基本操作。
Br
答案 0 :(得分:1)
我已经将您的代码片段带入了codeandbox中,对我来说似乎还可以,而您看不到其他人很难说出问题所在。也许与您如何导入和使用React Router有关。这是我的工作片段
// App
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Switch, Route } from "react-router";
import Page1 from "./Page1";
import Nav from "./Nav";
import UserProvider, { UserConsumer } from "./Provider";
import "./styles.css";
function App() {
return (
<UserProvider>
<Router>
<Nav />
<UserConsumer>
{state => <p>Username: {state.username}</p>}
</UserConsumer>
<Switch>
<Route exact path="/" component={Page1} />
</Switch>
</Router>
</UserProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
// Provider
import React from "react";
const UserContext = React.createContext();
// Create an exportable consumer that can be injected into components
export const UserConsumer = UserContext.Consumer;
// Create the provider using a traditional React.Component class
export default class UserProvider extends React.Component {
render() {
return (
// value prop is where we define what values
// that are accessible to consumer components
<UserContext.Provider
value={{
username: "Crunchy Crunch",
dateJoined: "9/1/18",
membershipLevel: "Silver"
}}
>
{this.props.children}
</UserContext.Provider>
);
}
}
这是工作代码和框的链接