【发布时间】:2018-04-25 22:24:33
【问题描述】:
我正在尝试将 React Router V4 与新的 React 上下文 API 一起使用。这是我的代码:
class App extends Component {
static propTypes = {
router: PropTypes.func.isRequired,
module: PropTypes.string.isRequired,
sideMenuConfig: PropTypes.string
};
render() {
let baseName = "/" + this.props.module;
// This will get my dashboard component, loading context from database
let navComponent = (
<MyCustomAppContextProvider>
<AppContext.Consumer>
{context =>
<Dashboard
context={context}
module={this.props.module}
router={router}
sideMenuConfig={this.props.sideMenuConfig}
/>
}
</AppContext.Consumer>
</MyCustomAppContextProvider>
);
let routes = null;
if (!isAuthenticated()) {
routes = <Auth
baseName={baseName}
/>;
} else {
routes = (
<Switch>
<Route exact path="/logout" component={Logout} />
<Route exact path="/auth" component={Logout} />
<Route exact path="/" component={navComponent} />
<Route
exact
path="/:screen"
component={navComponent}
/>
<Route
exact
path="/:screen/:action"
component={navComponent}
/>
<Route
exact
path="/:screen/:action/:id"
component={navComponent}
/>
<Route component={PageNotFoundError} />
</Switch>
);
}
return (
<BrowserRouter basename={baseName}>
{routes}
</BrowserRouter>
);
}
}
export default App;
router 包含一个路由器功能,它将根据导航路径加载我的屏幕。module 是模块名称。sideMenuConfig 是我的侧边菜单的 json 配置。
尝试运行时,我从反应路由器收到以下错误:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object
Check the render method of `Route`.
我希望在 Dashboard 中接收所有传递的道具以及 match 属性以运行路由器。
【问题讨论】:
-
应该是带点的
AppContext.Provider?另外,将Consumer渲染为Provider的直接子级有什么意义?错误来自反应。你试图渲染的东西是一个对象。你能添加堆栈跟踪吗?它发生在哪个组件中? -
这是新的上下文 API 表示法...查看official documentation。
Consumer从数据库中获取上下文以提供给Provider。该错误似乎发生在 react-router-v4 内部。没有明确的堆栈跟踪。 -
我知道新的 api,但我认为在同一个组件中使用 Provider 和 Consumer 没有任何意义。您在哪里使用数据填充上下文?
-
“没有清晰的堆栈跟踪”是什么意思?渲染组件时发生错误。打开您的浏览器控制台并查看在哪些组件中呈现。当您尝试渲染 javascript 对象时会发生此错误(您无法渲染对象)。它不是来自 react-router。
-
所以你的错误的原因可能只是我在第一条评论中指出的错字。它必须是
<AppContext.Provider>而不是<AppContextProvider>。但是仍然像这样使用上下文 api 绝对没有意义。
标签: javascript reactjs react-router-v4 react-context