2

我正在尝试将 React.createContext() 与反应路由器一起使用,但目前是不可能的。

const Context = React.createContext()

<Context.Provider value={{ valueTest: 1 }}>
  <HashRouter>
    <Switch>
      <Route
        exact
        path="/"
        render={() => <h1>HelloWorld</h1>} />
    </Switch>
  </HashRouter>
</Context.Provider>

我总是收到这个错误

未捕获的错误:元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。

有人能帮我吗?

4

1 回答 1

3

呈现您的上下文值似乎是一个问题,以下代码运行良好

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"));

上下文.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>
);

工作代码框

于 2018-04-30T16:57:25.153 回答