React Context apiを使用して、いくつかの状態を異なる子コンポーネントに渡しますが、が返されundefined
ます。
親コンポーネント:
export const UserContext = React.createContext();
export class Provider extends Component {
state = {
editGroup: false,
}
render() {
return (
<UserContext.Provider value={{
state: this.state
}}>
{this.props.children}
</UserContext.Provider>
)
}
}
子コンポーネント:
import { UserContext } from './index';
return (
<React.Fragment>
<UserContext.Consumer>
{(context) => (
<p>im inside the consumer {console.log(context)}</p>
)}
</UserContext.Consumer>
</React.Fragment>
);
この最後console.log
はとして戻ってきましたundefined
、私はここで何が間違っているのですか?
子コンポーネントで、コンシューマーセクションのコンテキストを値(関数パラメーター)に変更します。これは、プロバイダーに渡される小道具です。
<UserContext.Consumer>
{(value) => (
<p>im inside the consumer {console.log(value)}</p>
)}
</UserContext.Consumer>
完全に機能するサンプル
import React, { Component } from 'react'
const UserContext = React.createContext()
const Main = () => (
<Parent>
<Child/>
</Parent>
)
export default Main
//***************************************/
class Parent extends Component {
state = {
editGroup: false
}
render() {
return (
<UserContext.Provider value={{
state: this.state
}}>
{this.props.children}
</UserContext.Provider>
)
}
}
//***************************************/
const Child = () => {
return (
<React.Fragment>
<UserContext.Consumer>
{(value) => (
<p>Inside consumer {console.log(value)}</p>
)}
</UserContext.Consumer>
</React.Fragment>
);
}
//***************************************/
出力:状態:{editGroup:false}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加