【问题标题】:React Apollo client prop refetchQueries after mutation突变后 React Apollo 客户端道具 refetchQueries
【发布时间】:2019-02-17 03:27:44
【问题描述】:

我一直在阅读 Apollo 文档,但找不到任何关于如何在使用 withApollo HOC 传递的 client 道具发生突变后重新获取的示例。

我的组件:

import React, {Fragment} from 'react';
import gql from 'graphql-tag';
import { withApollo } from 'react-apollo';
...

const getPosts =  gql`
{
    posts {
    _id
    title
    description
    user {
        _id
    }
  }
}`;


const deletePost = gql`
    mutation deletePost($_id: String){
        deletePost(_id: $_id)
    }
`;

class PostList extends React.Component {
    static propTypes = {
        match: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired,
    };
    state = {posts: null};

    componentDidMount() {
        this.props.client.query({
                query: getPosts,
            }).then(({ data }) => {
                this.setState({ posts: data.posts });
            });
    }

    deletePost = postId => {
        this.props.client
            .mutate({
                mutation: deletePost,
                variables: {
                    _id: postId
                },
            })
            .then(({ data }) => {

                alert('Post deleted!');
            });
    };


    render() {
        const {posts} = this.state;    
        if (!posts) {
            return <div>Loading....</div>
        }

        return (
            <div className="post">
                ...stuff...
            </div>
        )
    }
}

export default withApollo(PostList);

我想在每次删除帖子时重新获取帖子。

【问题讨论】:

    标签: reactjs graphql apollo react-apollo


    【解决方案1】:

    您呈现的posts 数据处于组件状态,但您仅查询componentDidMount 中的帖子。仅当您的组件首次渲染时才会调用此方法。

    class PostList extends React.Component {
    
        fetchPosts() {
            this.props.client.query({
                    query: getPosts,
                }).then(({ data }) => {
                    this.setState({ posts: data.posts });
                });
        }
    
        componentDidMount() {
            this.fetchPosts();
        }
    
        deletePost = postId => {
            this.props.client
                .mutate({
                    mutation: deletePost,
                    variables: {
                        _id: postId
                    },
                })
                .then(({ data }) => {
                    this.fetchPosts()
                });
        };
    
    
        render() {
            const {posts} = this.state;    
            if (!posts) {
                return <div>Loading....</div>
            }
    
            return (
                <div className="post">
                    ...stuff...
                </div>
            )
        }
    }
    

    其实你甚至不需要本地状态,你可以依赖Apollo客户端本地缓存,使用Query组件以及Mutation组件。

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 2020-02-03
      • 2019-06-20
      • 2017-06-21
      • 2017-09-06
      • 2019-01-12
      • 2021-10-06
      • 2020-11-27
      • 2017-09-14
      相关资源
      最近更新 更多