首页 > 解决方案 > 只是在父组件中进行查询而不渲染任何东西并将所有数据作为道具发送

问题描述

我想在我的父组件中进行一个查询,而不是渲染任何东西并将该数据传递给某个子组件。我们如何在 react 和 graphql 中实现这一点?

               {
                   ({loading,error,data}) =>{
                     if(loading) return <h4>Loading...</h4>
                       if(error) console.log(error)
                       console.log("graphql data is ",data);

                       return(
                       <div className="body">
                                  </div>


                               </div>


                       );
                 }
               }

              </Query>

我想在我的父组件中进行此查询并将其作为子组件传递。如果是简单的 api,我可以简单地调用 api 并将其存储在我的 redux 中,然后将这些数据作为子属性获取。如何在不渲染任何东西的情况下实现相同的目标?

标签: reactjsgraphqlapollo

解决方案


你可以创建一个组件来渲染它的子组件。这是一个如何在反应中做到这一点的示例。

像这样的东西。

class Query extends Component {
  state = {
    loading: true,
    error: {},
    data: {}
  }
  componentDidMount() {
    //do the apicall here
    this.setState({ loading: false, data: { header: "may the force be with you" } });
  }

  render() {
    const { state: props, props: { children } } = this;

    // return the data here
    // passing state as props here after renaming state to props
    return children(props);
  }
}

使用反应状态而不是 redux。如果你想使用 redux,你可以制作这个连接的组件。并且像这样使用组件。

    <Query>
      {
        ({ loading, error, data }) => {
          if (loading) return <>Loading.......</>
          if (Object.keys(error).length > 0) return <>Some Error Handler</>
          if (data) return (
            <>
              <img src={logo} className="App-logo" alt="logo" />
              <a
                className="App-link"
                href="https://reactjs.org"
                target="_blank"
                rel="noopener noreferrer"
              >
                {data.header}
              </a>
            </>
          )
        }
      }
    </Query>

推荐阅读