为什么withApollo的查询没有收到道具?

时间:2017-08-11 06:07:09

标签: reactjs apollo react-apollo

下面的代码,当加载此组件时,它将发送两个查询,然后在生命周期方法中,我检查是否存在某些信息,例如本例中的id。如果此id存在,它将在此id上执行另一个查询。

问题是query是成功解决,而后data是我想要的真实信息,但我无法在 this.props.data 中找到它(渲染函数中this.props.data未定义)。

这种方法有什么问题,为什么this.props.data未定义?

class UserInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.wechat.wechatUser && nextProps.wechat.wechatUser.binded > 0) {
      const id = nextProps.wechat.wechatUser.binded;
      this.props.client
        .query({
          query: QUERY_PLAYER,
          fetchPolicy: 'network-only',
          variables: {
            id,
          },
        })
        .then(({ data }) => {
          console.log(data);
        });
    }
  }

  render() {
    if (this.props.data.player) {
      return (
        <div>
          {this.props.data.player.name}
        </div>
      );
    }

    return <div>loading</div>;
  }
}

const WECHATUSER_QUERY = gql`
  query WechatUser($id: Int!) {
    wechatUser(id: $id) {
      id
      nickname
      sex
      city
      province
      openid
      unionid
      headimgurl
      role_id
      game_id
      type_id
      parent_id
      tel
      disabled
      remainder
      created_at
      updated_at
      language
      weixin_account
      is_api_user
      binded
    }
  }
`;
const QUERY_TYPE = gql`
  {
    listAgentCategory {
      id
      name
      num
      price
      profit
      investment
    }
  }
`;

const QUERY_PLAYER = gql`
  query player($id: Int!) {
    player(id: $id) {
      id
      roomid
      headimg
      name
      sex
      lv
      exp
      coins
      gems
      roomid
      reg_time
      login_time
      logout_time
      online_time
      lock
      platform
      agent
    }
  }
`;

const withData = graphql(QUERY_TYPE, { name: 'agentType' })(
  graphql(WECHATUSER_QUERY, {
    name: 'wechat',
    options: props => ({
      fetchPolicy: 'network-only',
      variables: {
        id: JSON.parse(localStorage.getItem('userinfo')).user.id,
      },
    }),
  })(UserInfo)
);

export default withApollo(withData);

1 个答案:

答案 0 :(得分:0)

当您收到异步调用的结果时,您应该使用state。您无法修改props。惯例是在这样的场景中使用state对象。

constructor() {
    super();
    this.state = {
                   data: ''
                  };
}

然后,修改componentWillReceiveProps(),如下所示:

  this.props.client
    .query({
      query: QUERY_PLAYER,
      fetchPolicy: 'network-only',
      variables: {
        id,
      },
    })
    .then(({ data }) => {
          this.setState({
              'data': data
          });
       });
    });

然后在你的render()中使用它,如下所示:

<div>{this.state.data && this.state.data.name}</div>

希望这会对你有所帮助。 : - )

相关问题