[英]Undefined React context
我想傳遞一個值。
它來自非洲 -> FetchContext -> Jumbotron。 當它到達 Jumbotron 時,它是未定義的。
我認為這是因為非洲再也沒有被召喚過。
我將大陸的價值發送到一個上下文中。 這個想法是,這是一個旅游評論網站。 所有大陸都在導航欄中排序。 每當單擊導航欄中的“非洲”時,都會調用非洲組件。
const Africa = ({}) => {
return (
<div>
<DataProvider continent={["Africa"]} />
這是上下文:
const DataContext = React.createContext();
export default DataContext;
export class DataProvider extends Component {
constructor(props) {
super(props);
console.log("Props " + this.props.continent + " in fetchcontext.js");
this.state = {
title: '',
};
}
updateState() {
this.setState({
title: this.props.continent,
});
}
componentDidMount() {
console.log("Comp did mount: " + this.props.continent)
}
componentWillUnmount() {
console.log("Comp did unmount: " + this.props.continent)
}
render() {
return (
<DataContext.Provider value={{ value: this.props.continent }}>
{this.props.children}
</DataContext.Provider>
);
}
}
無論我在哪里控制台記錄 this.props.continent,它始終是正確的對應大陸。 但是,一旦我針對評論,我的 jumbotron 就會產生,而這里的值是未定義的。
這是我的大屏幕:
const JumbotronPage = () => {
return (
<section className="page-section">
<DataProvider>
<DataContext.Consumer>
{(value) => (
<MDBContainer>
{console.log(value)}
我確定這很愚蠢,但我無法弄清楚。 謝謝
TLDR; 我將 prop 傳遞給中間組件,將 prop 設置為 state,將 state 作為上下文發送給 jumbotron-component。 在這里,上下文是未定義的。
編輯:已解決。 我必須了解如何將它傳遞給它的孩子。
JumbotronPage
必須是DataProvider
的子級。
在您的情況下, this.props.children
未在DataProvider
中使用。
const DataContext = React.createContext();
const JumbotronPage = () => {
// ["Africa"]
return (
<DataContext.Consumer>
{value => {
console.log(value);
}}
</DataContext.Consumer>
);
};
class DataProvider extends React.Component {
render() {
return (
<DataContext.Provider value={this.props.continent}>
{this.props.children}
</DataContext.Provider>
);
}
}
const App = () => {
return (
<DataProvider continent={['Africa']}>
<JumbotronPage />
</DataProvider>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.