[英]React Native Context - retrieve the value from Context.provider outside of the render function
I have an app that already uses the context api, it has a number of providers.我有一个已经使用上下文 api 的应用程序,它有许多提供程序。 I have added a new provider called VideoContext.我添加了一个名为 VideoContext 的新提供程序。
All I want is to read its activeVideo value (set elsewhere in the app)我只想读取它的 activeVideo 值(在应用程序的其他地方设置)
class App extends Component {
state = {
videoState: 0,
};
setVideoState(){
//logic to alter the videoState.
}
...
render() {
return (
// Config Context
<ConfigContext.Provider value={this.decorateConfigContextFromProps()}>
<VideoContext.Provider value={this.state.videoState}>
{/* Theme Context */}
<SomeOtherProvider theme={this.decorateStyledContextFromProps()}>
{/* Redux Store Context */}
<Provider store={this.rootStore}>
<View style={{ flex: 1 }}>
<StatusBar />
<ConnectedApp />
</View>
</Provider>
</SomeOtherProvider>
</VideoContext.Provider>
</ConfigContext.Provider>
);
}
}
App.contextType = ConfigContext;
child component - miles down the tree子组件 - 树下数英里
class DeepChild extends Component {
state = {
activeVideo: '',
};
shouldComponentUpdate(nextProps: Props, nextState) {
if (this.state.activeVideo !== nextState.activeVideo) {
return true;
}
return //otherwise do some other logic here
}
...
render() {
return (
<View/>
<VideoContext.Consumer>
/* yuck! */
{({activeVideo}) => {
if(activeVideo !== this.state.activeVideo){
this.setState({activeVideo: activeVideo}, () => {
console.log('this did indeed update the state');
})
}
}}
</VideoContext.Consumer>
<FlatList...containing many items.../>
</View>
);
}
}
How can I read the value provided by the VideoContext Provider inside the Child class component, without having to bury it inside the render function?如何读取子 class 组件内 VideoContext Provider 提供的值,而不必将其埋入渲染器 function 内? I haven't seen any docs on this.我还没有看到任何文档。
Thanks.谢谢。
Use contextType like this像这样使用 contextType
static contextType = VideoContext;
then value will be accessible like this.context.activeVideo那么值将像 this.context.activeVideo 这样访问
eg例如
class DeepChild extends Component {
static contextType = VideoContext;
state = {
activeVideo: '',
};
shouldComponentUpdate(nextProps: Props, nextState) {
if (this.state.activeVideo !== nextState.activeVideo) {
return true;
}
return //otherwise do some other logic here
}
...
render() {
return (
<View/>
<VideoContext.Consumer>
/* yuck! */
{({activeVideo}) => {
if(activeVideo !== this.state.activeVideo){
this.setState({activeVideo: activeVideo}, () => {
console.log('this did indeed update the state');
})
}
}}
</VideoContext.Consumer>
<FlatList...containing many items.../>
</View>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.