我有这段代码:
const defaultValue = new Api()
const ApiContext = React.createContext(defaultValue);
const ApiProvider = ApiContext.Provider;
const ApiConsumer = ApiContext.Consumer;
const withApi = (Enhanced: any) => {
return (
<ApiConsumer>
{api => {
return <Enhanced api={api}/>;
}}
</ApiConsumer>
)
}
export default ApiContext;
export {ApiContext, ApiProvider, ApiConsumer, withApi};
在我的应用中,我有这样的东西:
const api = new ApiManager({...});
ReactDOM.hydrate(
<Provider store={store}>
<BrowserRouter>
<ApiProvider value={api}>
<Main />
</ApiProvider>
</BrowserRouter>
</Provider>, document.querySelector('#app')
);
但是此行return <Enhanced api={api}/>;
会导致以下错误:
1。
警告:React.createElement:类型无效-预期为字符串 (对于内置组件)或类/函数(对于复合 组件),但得到:。你是不是偶然 导出JSX文字而不是组件?
2。
未捕获的不变变量:元素类型无效:预期a 字符串(对于内置组件)或类/函数(对于复合 组件),但得到了:对象。
3。
Uncaught (in promise) Invariant Violation: 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 `Context.Consumer`.
我在这里做错了什么? 如何将api属性传递给增强型组件?
[编辑]
这就是我调用组件的方式:
App.tsx
class App extends React.Component {
render() {
return (
<React.Fragment>
<Switch>
{routes.map(({ path, exact, component: C }) => {
return <Route
key={path}
path={path}
exact={exact}
render={(props) => {
return withApi(<C {...props} />);
}} />
})}
</Switch>
</React.Fragment>
)
}
}
答案 0 :(得分:1)
您没有正确编写withApi HOC。它应该返回一个功能组件而不是JSX
const withApi = (Enhanced: any) => {
return (props) => {
return (
<ApiConsumer>
{api => {
return <Enhanced {...props} api={api}/>;
}}
</ApiConsumer>
)
}
}
并像使用它
class App extends React.Component {
render() {
return (
<React.Fragment>
<Switch>
{routes.map(({ path, exact, component: C }) => {
const Comp = withApi(C);
return <Route
key={path}
path={path}
exact={exact}
render={(props) => {
return <Comp {...props}/>
}} />
})}
</Switch>
</React.Fragment>
)
}
}