我正在尝试将React.createContext((与反应路由器一起使用,但目前是不可能的。
const Context = React.createContext()
<Context.Provider value={{ valueTest: 1 }}>
<HashRouter>
<Switch>
<Route
exact
path="/"
render={() => <h1>HelloWorld</h1>} />
</Switch>
</HashRouter>
</Context.Provider>
我总是收到此错误
未捕获错误:元素类型无效:需要字符串(对于内置组件(或类/函数(对于复合组件(,但得到:对象。
有人可以帮助我吗?
呈现上下文值似乎是一个问题,以下代码运行良好
索引.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"));
上下文.js
import React from "react";
export const Context = React.createContext();
你好.js
import React from "react";
import { Context } from "./context";
export default ({ name }) => (
<Context.Consumer>
{value => (
<h1>
Hello {name} {value.valueTest}!
</h1>
)}
</Context.Consumer>
);
工作代码沙箱