如何将 React.createContext() 与反应路由器一起使用?
How to use React.createContext() with react router?
我正在尝试将 React.createContext() 与 React 路由器一起使用,但目前是不可能的。
const Context = React.createContext()
<Context.Provider value={{ valueTest: 1 }}>
<HashRouter>
<Switch>
<Route
exact
path="/"
render={() => <h1>HelloWorld</h1>} />
</Switch>
</HashRouter>
</Context.Provider>
我总是遇到这个错误
未捕获错误:元素类型无效:应为字符串(对于内置组件)或 class/function(对于复合组件)但得到:对象。
有人可以帮助我吗?
渲染上下文值似乎是个问题,以下代码运行良好
index.js
import React from "react";
import { render } from "react-dom";
import { HashRouter, Switch, Route } from "react-router-dom";
import Hello from "./Hello";
import { Context } from "./context";
const App = () => (
<Context.Provider value={{ valueTest: 1 }}>
<HashRouter>
<Switch>
<Route
exact
path="/"
render={props => <Hello {...props} name="CodeSandbox" />}
/>
</Switch>
</HashRouter>
</Context.Provider>
);
render(<App />, document.getElementById("root"));
context.js
import React from "react";
export const Context = React.createContext();
Hello.js
import React from "react";
import { Context } from "./context";
export default ({ name }) => (
<Context.Consumer>
{value => (
<h1>
Hello {name} {value.valueTest}!
</h1>
)}
</Context.Consumer>
);
我正在尝试将 React.createContext() 与 React 路由器一起使用,但目前是不可能的。
const Context = React.createContext()
<Context.Provider value={{ valueTest: 1 }}>
<HashRouter>
<Switch>
<Route
exact
path="/"
render={() => <h1>HelloWorld</h1>} />
</Switch>
</HashRouter>
</Context.Provider>
我总是遇到这个错误
未捕获错误:元素类型无效:应为字符串(对于内置组件)或 class/function(对于复合组件)但得到:对象。
有人可以帮助我吗?
渲染上下文值似乎是个问题,以下代码运行良好
index.js
import React from "react";
import { render } from "react-dom";
import { HashRouter, Switch, Route } from "react-router-dom";
import Hello from "./Hello";
import { Context } from "./context";
const App = () => (
<Context.Provider value={{ valueTest: 1 }}>
<HashRouter>
<Switch>
<Route
exact
path="/"
render={props => <Hello {...props} name="CodeSandbox" />}
/>
</Switch>
</HashRouter>
</Context.Provider>
);
render(<App />, document.getElementById("root"));
context.js
import React from "react";
export const Context = React.createContext();
Hello.js
import React from "react";
import { Context } from "./context";
export default ({ name }) => (
<Context.Consumer>
{value => (
<h1>
Hello {name} {value.valueTest}!
</h1>
)}
</Context.Consumer>
);