【问题标题】:How to access mutation data from component?如何从组件访问突变数据?
【发布时间】:2019-05-05 12:26:13
【问题描述】:

这是我扩展组件的方式:

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 方法中做到这一点?

【问题讨论】:

    标签: javascript graphql react-apollo apollo-client


    【解决方案1】:

    关于 apollo-client docs,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,
            });
        })
    }
    

    【讨论】:

    • 我收到构造函数不能异步的错误。
    • 你说得对,看来我只是修改了答案。
    • 然而这使得loading 无法使用。我没有收到任何新的render 电话loading true。只有在数据准备好后,状态才会改变并调用渲染。加载总是错误的。
    • 您说的对,我建议在构造函数中将初始加载状态设置为true,并在您处理突变响应的成功或错误时将其设置为false,这样您就可以确保加载突变持续时间结束时将停止。将根据该修改答案
    • 这只是模拟部分加载状态。例如,即使他与互联网断开连接,用户也可能会看到“正在加载”。当模拟加载状态不正确时,可能还有其他情况。它没有给出实际状态。
    猜你喜欢
    • 2019-08-01
    • 2016-11-22
    • 2019-11-05
    • 2021-09-04
    • 2017-10-03
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    相关资源
    最近更新 更多