React Context 消费者找不到道具
React Context consumer can't find props
我正在尝试使用 React Context API 来传递道具,但是我遇到了 "undefined" 错误。 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 {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;
我在这里找不到任何问题,但是控制台报这个错误:TypeError: Cannot read property 'rootPath' of undefined
,错误发生在这里:({rootPath}) => <span>{rootPath}</span>
关于使用 default value:
If there is no Provider for this context above, the value argument
will be equal to the defaultValue that was passed to createContext().
但是你正在用 Provider 包装它。尝试删除提供商:
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 Context API 来传递道具,但是我遇到了 "undefined" 错误。 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 {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;
我在这里找不到任何问题,但是控制台报这个错误:TypeError: Cannot read property 'rootPath' of undefined
,错误发生在这里:({rootPath}) => <span>{rootPath}</span>
关于使用 default value:
If there is no Provider for this context above, the value argument will be equal to the defaultValue that was passed to createContext().
但是你正在用 Provider 包装它。尝试删除提供商:
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>
)
}
}