首页 > 解决方案 > 如何从组件访问突变数据?

问题描述

这就是我扩展组件的方式:

const ComponentWithMutation = graphql(GQL_MUTATION_ACTIVATE, 
    {
        options: (props) => ({
            variables: {
                foo: props.foo,
                bar: props.bar,
            },
        }),
    })(ActivateEmail);

现在在组件内部:

class ActivateEmail extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        const { match, mutate } = this.props;
        mutate({
            variables: { token: match.params.atoken },
        });
    }

    render() {
        return (
            <div>
                // I need to access data, error, loading here...
            </div>
        );
    }
}

我想访问data, error, loading. 我怎样才能在render方法中做到这一点?

标签: javascriptgraphqlreact-apolloapollo-client

解决方案


关于 apollo-client文档,mutation 返回一个 promise,该 promise 返回诸如数据、错误、加载等突变信息。

所以代码应该是这样的:

constructor() {
    this.state = {
        dataLoading: true,
        dataLoadError: false,
    }
}

async componentDidMount() {
    try {
        const { match, mutate } = this.props;
        const { data: { yourMutationData }, error} = await mutate({
            variables: { token: match.params.atoken },
        });
        this.setState({
            dataLoading: false,
            data: yourMutationData 
        });
    }
    catch (err) {
        this.setState({
            dataLoading: false,
            dataLoadError: true,
        });
    }
}

或者你可以使用这样的普通承诺:

componentDidMount() {
    const { match, mutate } = this.props;
    mutate({
        variables: { token: match.params.atoken },
    })
    .then( (query) => {
        console.log(query); //here you should get the same result with the code above.
        this.setState({
            dataLoading: false,
            data: query.data.yourMutationData 
        });
    })
    .catch(err => {
        this.setState({
            dataLoading: false,
            dataLoadError: true,
        });
    })
}

推荐阅读