【问题标题】:Gatsby - Updating context data on page loadGatsby - 在页面加载时更新上下文数据
【发布时间】:2020-05-15 12:43:23
【问题描述】:

我正在使用 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。单击“关于”页面可以正常工作;如果您然后单击“changer”,它会更新并成功从上下文中读取新状态。但是,如果您单击投资组合页面,我尝试在第一次渲染时更新,它会引发一堆错误。再次感谢您的帮助。

【问题讨论】:

  • 您想要达到的结果是什么?阅读the plugin's docs,您似乎不需要在组件挂载时设置上下文。
  • 我试图在每次页面重新加载时触发动画。这需要在布局级别(页面上方),这样它就不会在中途重新渲染。
  • 您是否尝试使用componentDidMount?你可以像在任何 React 应用中一样使用lifecycle methods
  • 谢谢,我会试一试的。

标签: reactjs gatsby


【解决方案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>
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2019-05-13
    • 1970-01-01
    • 2020-11-03
    • 2011-04-30
    • 1970-01-01
    • 2015-09-10
    相关资源
    最近更新 更多