我正在使用Gatsby布局插件,并希望使用当前显示的页面更新上下文提供程序中的状态。我可以通过单击按钮来更新它,如以下代码所示:
import ContextConsumer from "../components/Context.js"
class Portfolio extends React.Component {
constructor (props){
super(props)
this.state = {
page: "portfolio"
}
}
render(){
return (
<React.Fragment>
<ContextConsumer>
{({ data, set }) => (
<button onClick={() => set({curPage:this.state.page})}>Click</button>
)}
</ContextConsumer>
<h1>This is the portfolio page</h1>
</React.Fragment>
)
}
}
但是,我希望上下文在页面加载时更新。我尝试使用立即调用的箭头功能,但这会导致错误“超出最大更新深度”。
更新10.2:这仍然让我感到困惑。我可以通过单击按钮成功更新和读取上下文,但是仍然无法使其在页面加载或生命周期方法中正常工作。如果您查看此沙盒,您将明白我的意思:codesandbox.io/s/thirsty-frog-ocnzl。单击“关于”页面可以正常工作;如果您随后单击“转换器”,它将更新并成功从上下文中读取新状态。但是,如果单击投资组合页面(我尝试在第一次渲染上进行更新),则会引发很多错误。再次感谢您的帮助。
答案 0 :(得分:1)
对于其他为此奋斗的人,我发现了一个解决方案,该解决方案是将您的组件包装到更高阶的组件中,并将上下文数据作为道具传递。这是一个示例:
//This is the original component
class Portfolio extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.props.set({ curPage: "portfolio" })
}
render(){
return(
<h1>This is the {this.props.data.curPage} page</h1>
);
}
}
//...and this is the component that wraps it to pass in context data as a prop.
const PortfolioWrap = () => (
<ContextConsumer>
{({ data, set }) => (
<Portfolio data={data} set={set}/>
)}
</ContextConsumer>
)