首页 文章

Gatsby Graphql跳过

提问于
浏览
0

我试图通过一个增加state.count的按钮从graphql中翻阅Gatsby中的react组件中的数据 .

当我单击该按钮时,state.count会递增但不会传递给查询 .

我有什么想法我做错了吗?

pageUp=() => {
this.setState({count: this.state.count +2});
let skip=this.state.count
}

render() {
return (
  <StaticQuery
    query={graphql`
      query ListingPageQuery ($skip:Int){
        allMarkdownRemark(
          limit:2
          skip: $skip
          ) 
          {
          ...
        }
      }
    `
    }...

3 回答

  • 1

    我在这段代码中看到了两个问题 . 第一:

    pageUp=() => {
        let skip=this.state.count
    }
    

    let 语句使 skip 变量成为此函数的本地变量 . 它_1154486_是一个成员变量或其他东西,这个语句会影响它,你正在设置一个纯粹的局部变量,其状态将会丢失 .

    第二:

    this.setState({count: this.state.count +2});
    let skip=this.state.count
    

    State updates may be asynchronous,并且React文档明确建议不要改变状态(有一种基于回调的模式,'s more appropriate). The other consequence of this is that the state may not have actually updated when you get to the next line, so you'将"old"从"old"状态分配给 skip 变量 .

    查看Gatsby文档,有一个特定的注释StaticQuery does not support GraphQL variables,虽然浏览它并不建议另一个路径 . (显示可能分页数据的每个示例仅显示第一页 . )

  • 1

    你不能用盖茨比做到这一点 . GraphQL仅在构建时发生,而不是在客户端上发生 . 您想要获取所有内容,然后使用JS仅显示/跳过您想要显示的内容 .

    查看Gatsby文档,有一个特别注意,StaticQuery不支持GraphQL变量,但浏览它并不表示另一个路径 .

    此外,正如David Maze所说,StaticQuery不能在普通查询中工作,因为这些变量需要通过上下文传递 . https://next.gatsbyjs.org/docs/creating-and-modifying-pages/

    只有当你通过上下文传递它时,它才会在 pageContext 中提供,并作为查询中的变量(通常用于模板) .

  • 0

    setState()是异步的 . 捕获状态的正确方法是在回调中,也使用 prev 参数来引用setState()中的状态:

    this.setState(prev => ({
        count: prev.count + 2
    }), () => {
        // here this.state.count was updated and safe to use
    });
    

    参考:https://reactjs.org/docs/react-component.html#setstate

相关问题