【问题标题】:Need to use setstate() of data received from GraphQL subscription in react-apollo需要在 react-apollo 中使用从 GraphQL 订阅接收到的数据的 setstate()
【发布时间】:2019-05-31 15:51:28
【问题描述】:

我正在尝试通过 react-apollo 设置 GraphQL 订阅查询的 setState()。我的目的是存储我从 GraphQL 收到的完整对象,并将其保存到 App.js 文件的 ComponentDidMount() 方法中的状态中。

我已经尝试了很多方法让它工作,例如 react-apollo 的SubscribetoMore 端点,但我认为我正在为它编写错误的反应代码。

/App.js

const haveAnyFish = () => (
    <Subscription subscription={gql`${SUBSCRIPTION_SYNC}`} >
{({ loading, error, data }) => {
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :</p>;
  return (
    <div>
      <div>{fishes(data)}</div>
    </div>
  );
}}
</Subscription>
);

/App.js

class App extends React.Component {
    state = {
      fishes: {},
      order: {}
    };
componentDidMount() {
    const fishes = (data) => {
        this.setState({ fishes: data });
    }
  }

订阅查询

const SUBSCRIPTION_SYNC = `
    subscription syncState{
      cotd {
      _id_2
      name
      desc
      image
      price
      status
    }
  }`;

【问题讨论】:

    标签: javascript reactjs graphql react-apollo graphql-subscriptions


    【解决方案1】:

    您不需要在您的情况下使用 componentDidMount。您在 componentDidMount 方法中定义了函数,并且无法在外部访问

    改变

       componentDidMount() {
            const fishes = (data) => {
                this.setState({ fishes: data });
            }
        }
    

      fishes = data => {
            this.setState({ fishes: data });
      }
    

    改变

        const haveAnyFish = () => (
            <Subscription subscription={gql`${SUBSCRIPTION_SYNC}`} >
              {({ loading, error, data }) => {
                  if (loading) return <p>Loading...</p>;
                  if (error) return <p>Error :</p>;
               return (
                 <div>
                    <div>{this.fishes(data)}</div>
                    </div>
                 );
               }}
             </Subscription>
            );
    

         haveAnyFish = () => (
              <Subscription subscription={gql`${SUBSCRIPTION_SYNC}`} >
             {({ loading, error, data }) => {
              if (loading) return <p>Loading...</p>;
              if (error) return <p>Error :</p>;
                 return (
                    <div>
                      <div>{this.fishes(data)}</div>
                    </div>
                  );
               }}
            </Subscription>
          );
    

    您必须在没有 this 的情况下在组件中调用 haveAnyFish 函数,因此在上述代码更改后,您需要使用 this.haveAnyFish 调用 haveAnyFish 函数

    另外请注意,每当您在组件内创建函数时,它们不需要在函数之前使用 const,如果您想访问这些函数内的状态或道具,您需要手动绑定它们或将它们更改为箭头函数

    【讨论】:

      猜你喜欢
      • 2017-09-01
      • 2022-12-12
      • 2017-09-19
      • 2020-10-08
      • 2020-02-05
      • 2020-11-08
      • 2022-12-12
      • 2020-08-03
      • 2020-07-07
      相关资源
      最近更新 更多