Javascript React setState不触发上下文重新渲染
我有一个React组件,它在发出请求后更新其状态。 在这个组件的render函数中,我创建了一个上下文提供程序,并传入状态的值Javascript React setState不触发上下文重新渲染,javascript,reactjs,Javascript,Reactjs,我有一个React组件,它在发出请求后更新其状态。 在这个组件的render函数中,我创建了一个上下文提供程序,并传入状态的值 class App extends React.Component { constructor(props) { super(props); this.state = { text: 'defaultValue', } } componentDidMount() {
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;
但是,SomeComponent
中上下文中的值是“defaultValue”,而不是更新后的值
最终控制台日志为:
defaultValue
defaultValue
updatedValue
难道不是吗
defaultValue
defaultValue
updatedValue
updatedValue
因为更新值时,应触发重新渲染并更新上下文。这里缺少什么?
某些组件的构造函数()
仅在组件装载时调用,而不是在重新呈现时调用。为了查看新的上下文值,您需要将console.log(this.context.text)
放入其render()
或类似componentdiddupdate()之类的生命周期方法中SomeComponent是否包含render()方法?如果否,则不会发生重新加载。updatedValue由父渲染方法打印。
defaultValue
defaultValue
updatedValue
updatedValue