考虑以下情况:
public images: Image[];
import React, { Component } from 'react';
import LocaleService from '../Services/LocaleService.js';
const defaultStore = {
loaded: false,
locales: []
};
const LocalesContext = React.createContext(defaultStore);
class LocalesProvider extends Component
{
state = defaultStore;
load() {
const service = new LocaleService(), that = this;
service.fetch().then(function (locales) {
that.setState({ locales: locales, loaded: true });
});
}
data() {
return this.state;
}
componentDidMount() {
this.load();
}
render() {
return (
<LocalesContext.Provider value={this.data()}>
{this.props.children}
</LocalesContext.Provider>
);
}
}
export default LocalesProvider;
import React, { Component } from 'react';
import Sidebar from './Sidebar.js';
import Topbar from './Topbar.js';
import Content from './Content.js';
import LocalesProvider from './Providers/LocalesProvider.js';
class App extends Component
{
state = {
ready: true
}
render() {
if (this.state.ready) {
return (
<div>
<Topbar/>
<section className="section">
<section className="columns" style={{height: '100vh'}}>
<div>
<LocalesProvider.Consumer>
{ data =>
(
<Sidebar isReady={data.loaded} locales={data.locales}/>
)
}
</LocalesProvider.Consumer>
</div>
<main className="column" style={{overflow: 'auto', position: 'relative'}}>
<Content/>
</main>
</section>
</section>
</div>
);
} else {
return ('Loading...');
}
}
}
export default App;
元素类型无效:期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:undefined。您可能忘记从其定义的文件中导出组件,或者您可能混淆了默认导入和命名导入。
答案 0 :(得分:3)
LocalesProvider
是组件,而不是上下文,因此它没有Consumer
属性。我没有对它进行过测试,但是如果导出创建的上下文,它可能会有效:
export const LocalesContext = React.createContext(defaultStore);
将您的导入更改为
import LocalesProvider, { LocalesContext } from './Providers/LocalesProvider.js';
并将<LocalesProvider.Consumer>
替换为<LocalesContext.Consumer>
。