我需要发出一个新的 api 请求来获取给定 dataId 的数据。这个值存在于上下文中。
import { MyContext } from './Context'
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = {
dataId: this.context.state.dataId // tried setting state first but didn´t work.
}
this.details = this.details.bind(this)
}
details() {
fetch('https://api.mydomain.com/' + this.context.state.dataId)
.then(response => response.json())
.then(data => this.setState({ data: data }));
}
componentDidMount() {
this.details()
}
render() {
return(
<MyContext.Consumer>
{(context) => (
<div>data: {JSON.stringify(data)} dataId: {context.state.dataId}</div>
)}
</MyContext.Consumer>
)
}
}
MyComponent.contextType = MyContext;
export default MyComponent
从其他组件我可以设置新值,如
this.context.setDataId(1)
这将正确显示,但问题是没有进行新的获取以获取在上下文中更改的 dataId 的新数据。不知道什么是正确的生命周期方法我可以用来检测上下文中的更改并对 this.details()进行新调用
我没有在这里添加上下文代码,因为它工作正常。但如果你需要看,请告诉我。
相关分类