test.js
export default class TestScreen extends React.Component {
static contextType= AppProvider;
componentDidMount() {
console.log('test',this.context);
}
render() {
return (
<AppConsumer>
{ (context) => (
<p>{context.favoriteAnimal}</p>
)}
</AppConsumer>
)
}
}
store.js
const initialState = {
favoriteAnimal: "cow",
};
export const AppContext = React.createContext();
export const AppConsumer = AppContext.Consumer;
export class AppProvider extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
}
render() {
return (
<AppContext.Provider value={{
favoriteAnimal: this.state.favoriteAnimal,
}}>
{this.props.children}
</AppContext.Provider>
);
}
}
依赖性:{ “ react”:“ ^ 16.8.4”, “ react-dom”:“ ^ 16.8.4”, “反应脚本”:“ 2.1.8” }
this.context为空{} , 在test.js中。无法找到出路,任何帮助将不胜感激。谢谢
答案 0 :(得分:3)
问题是您正在将ContextType
分配给AppProvider
,这是您的组件,而不是React.createContext
返回的上下文。进行更改后,您甚至不需要在渲染方法中使用AppConsumer
export default class TestScreen extends React.Component {
static contextType= AppContext;
componentDidMount() {
console.log('test',this.context);
}
render() {
return (
<p>{this.context.favoriteAnimal}</p>
)
}
}