Reactjs 反应上下文消费者可以';我找不到道具
我试图使用React上下文API来传递道具,但出现了“未定义”错误。react的版本是16.3.2,react dom的版本是16.3.2。以下是我的代码: Provider.jsx:Reactjs 反应上下文消费者可以';我找不到道具,reactjs,react-context,Reactjs,React Context,我试图使用React上下文API来传递道具,但出现了“未定义”错误。react的版本是16.3.2,react dom的版本是16.3.2。以下是我的代码: Provider.jsx: import React from 'react'; export const PathContext = React.createContext({ rootPath: "http://localhost/example" }); App.jsx: import React from 'react';
import React from 'react';
export const PathContext = React.createContext({
rootPath: "http://localhost/example"
});
App.jsx:
import React from 'react';
import {PathContext} from './Provider.jsx';
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div>
<PathContext.Provider>
<AppRootPath />
</PathContext.Provider>
</div>
)
}
}
class AppRootPath extends React.Component {
render() {
return(
<div>
<span>App Root Path</span><br />
<PathContext.Consumer>
{
({rootPath}) => <span>{rootPath}</span>
}
</PathContext.Consumer>
</div>
)
}
}
export default App;
从“React”导入React;
从“./Provider.jsx”导入{PathContext};
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
)
}
}
类ApprotPath扩展了React.Component{
render(){
返回(
应用程序根路径
{
({rootPath})=>{rootPath}
}
)
}
}
导出默认应用程序;
我在这里找不到任何问题,但控制台报告此错误:TypeError:无法读取未定义的
的属性'rootPath',错误发生在这里:({rootPath})=>{rootPath}
关于使用:
如果上面的上下文中没有提供程序,则value参数
将等于传递给createContext()的defaultValue
但您正在用提供者包装它。尝试删除提供程序:
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div>
<AppRootPath />
</div>
)
}
}
class AppRootPath extends React.Component {
render() {
return(
<div>
<span>App Root Path</span><br />
<PathContext.Consumer>
{
({rootPath}) => <span>{rootPath}</span>
}
</PathContext.Consumer>
</div>
)
}
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
}
render(){
返回(
)
}
}
类ApprotPath扩展了React.Component{
render(){
返回(
应用程序根路径
{
({rootPath})=>{rootPath}
}
)
}
}