如何使用 Context API 从另一个组件获取数据,接受数据的组件应该是 React.Component
(不在函数组件中) .
我想获取驻留在 Context 中的数据。提供者作为一个组件。 我在谷歌上搜索了如何使用 React Context API,所有答案都是基于使用功能组件,而不是 React。组件。
因为我不知道如何使用 Context API 从其他组件获取数据,所以我尝试了 PubSub-JS,但现在我想使用 Context API。
我有一个使用 Context API 的组件,我想从下面的组件获取数据。
import React, {Component} from "react";
import axios from "axios";
const VideoInformationContext = React.createContext();
class VideoContext extends Component{
constructor(props){
super(props);
this.state = {
videoIdx: props.videoIdx
videoList:null,
theme:null
}
}
componentDidMount(){
this.loadResource();
}
loadResource(){
axios({
url:`<TEST SERVER>?videoIdx=${this.state.videoIdx}`,
method:"get"
}).then(response => {
this.setState({
videoList:response.data.videosAndTheme.videoList,
theme:response.data.videosAndTheme.theme
});
});
}
render(){
return (
<VideoInformationContext.Provider value={this.state}>
{this.props.children}
</VideoInformationContext.Provider>
);
}
}
export const VideoinformationConsumer = VideoInformationContext.Consumer;
export default VideoContext;
所以我的问题是我想在 React 的 ComponentDidMount()
方法中获取数据。从上面的组件中获取组件。
最佳答案
在消费者组件中,您可以使用 static contextType = MyContext;
设置上下文,因此您的提供者组件将如下所示:
import React, {Component} from "react";
import axios from "axios";
export const VideoInformationContext = React.createContext();
class VideoContext extends Component{
constructor(props){
super(props);
this.state = {
videoIdx: props.videoIdx
videoList:null,
theme:null
}
}
componentDidMount(){
this.loadResource();
}
loadResource(){
axios({
url:`<TEST SERVER>?videoIdx=${this.state.videoIdx}`,
method:"get"
}).then(response => {
this.setState({
videoList:response.data.videosAndTheme.videoList,
theme:response.data.videosAndTheme.theme
});
});
}
render(){
return (
<VideoInformationContext.Provider value={this.state}>
{this.props.children}
</VideoInformationContext.Provider>
);
}
}
export default VideoContext;
您的消费者组件将如下所示:
import React, { Component } from 'react';
import { VideoInformationContext } from '--the location of your provider component--';
class MyConsumerComponent extends Component {
static contextType = VideoInformationContext;
componentDidMount(){
// you can use it here like this
const videoList = this.context.videoList;
}
render() {
//or you can use it here like this
return <p>{this.context.videoIdx}</p>;
}
}
export default MyConsumerComponent;
因此,在您的提供者组件中,像我上面那样导出创建的上下文,然后在您的消费者组件中,从您设置上下文的任何地方导入上下文,然后在您的类中设置静态 contextType,然后您可以在组件中的任何位置访问它并在渲染中使用 this.context
。
关于javascript - 如何通过 Context API 获取 React.Component 类中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55448216/