これは私のApp.jsです。コンテキストAPIを使用していますが、子コンポーネント、つまりNeighbourにある{context.country}と{context.job}でデータをフェッチできません。これは私のApp.jsです。コンテキストAPIを使用していますが、子コンポーネント、つまりNeighbourにある{context.country}と{context.job}でデータをフェッチできません。App.js
import React, { Component } from 'react';
import Neighbour from './Neighbour';
const MyContext = React.createContext();
class MyProvider extends Component {
state = {
firstName: 'Tom', lastName: 'Holland', age: 24, country: 'America', job: 'Actor',
}
render() {
return (
<MyContext.Provider value={{
state: this.state, growOld: () => this.setState({ age: this.state.age + 1 })
}}>
{this.props.children}
</MyContext.Provider>
);
}
}
class App extends Component {
render() {
return (
<div className="App">
<MyProvider value={{ state: this.state }}>
<div>
<p>I am in App component</p>
<Family />
<br />
<Neighbour />
</div>
</MyProvider>
</div>
);
}
}
export default App;
Neighbour.js
import React, { Component } from 'react';
const MyContext = React.createContext();
class Neighbour extends Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<MyContext.Consumer>
{context => (
<React.Fragment>
<p>Country : {context.country}</p>
<p>Job : {context.job}</p>
</React.Fragment>
)}
</MyContext.Consumer>
</div>
);
}
}
export default Neighbour;
値をオブジェクト{state: this.state}
としてコンテキストに提供しているのでcontext.state.country
、コンシューマーのように使用する必要があります。
<MyContext.Consumer>
{context => (
<React.Fragment>
<p>Country : {context.state.country}</p>
<p>Job : {context.state.job}</p>
</React.Fragment>
)}
</MyContext.Consumer>
またはあなたは次のようなプロバイダーに価値を提供します
<MyProvider value={this.state}>
<div>
<p>I am in App component</p>
<Family />
<br />
<Neighbour />
</div>
</MyProvider>
また、Neighbour
コンポーネントで、を持たないコンテキストを再度作成しているProvider
ため、Consumerの値が未定義になるため、Provider
で使用したのと同じコンテキストをインポートする必要があります。
Neighbour.jsで
Neighbour.js
import React, { Component } from 'react';
inport { MyContext } from 'path/to/context';
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加