[英]React setState not triggering a re-render with Contexts
我有一个 React 组件,它在发出请求后更新其 state。 在这个组件的渲染 function 中,我正在创建一个上下文提供程序并传入 state 的值。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: 'defaultValue',
}
}
componentDidMount() {
makeAxiosRequest()
.then((response) => {
this.setState({
text: 'updatedValue'
})
})
.catch((error) => {
console.log(error)
})
}
render() {
console.log(this.state.text)
return (
<div>
<MyContext.Provider value={{
text: this.state.text
}}>
<SomeComponent />
</MyContext.Provider>
</div>
)
}
}
export default App;
然后,在子组件中,我试图从上下文中获取该值。
class SomeComponent extends React.Component {
static contextType = MyContext;
constructor(props, context) {
super(props, context);
console.log(this.context.text)
}
}
但是, SomeComponent
中上下文中的值是“defaultValue”,而不是更新后的值。
最终的控制台日志是:
defaultValue
defaultValue
updatedValue
不应该是
defaultValue
defaultValue
updatedValue
updatedValue
因为当值更新时,应该触发重新渲染并更新上下文。 我在这里想念什么?
SomeComponent
的constructor()
仅在组件挂载时调用,而不是在重新渲染时调用。 为了查看新的上下文值,您需要将console.log(this.context.text)
放在它的render()
或像componentDidUpdate()
这样的生命周期方法中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.