【发布时间】:2020-09-02 15:23:40
【问题描述】:
我有一个已经使用上下文 api 的应用程序,它有许多提供程序。我添加了一个名为 VideoContext 的新提供程序。
我只想读取它的 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;
子组件 - 在树下数英里
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>
);
}
}
如何在 Child 类组件中读取 VideoContext Provider 提供的值,而不必将其埋在渲染函数中?我还没有看到任何关于此的文档。
谢谢。
【问题讨论】:
标签: javascript reactjs react-native