javascript - 如何从组件访问突变数据?
问题描述
这就是我扩展组件的方式:
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
方法中做到这一点?
解决方案
关于 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,
});
})
}
推荐阅读
- python-3.x - Http Trigger-Python-Log 特定消息不断,而不是 URL 正文或有效负载
- javascript - 如何在 blazor webassembly 中使用折叠边栏
- asp.net - 如果使用 Azure AD 保护的自定义 REST API,MSAL 是否能够维护令牌缓存并在令牌即将过期时为您刷新令牌
- usb-drive - 在 Raspberry Pi 上自动挂载的 USB 插入上执行间歇性故障
- javascript - React - 可以在表单中使用浏览器中的后退按钮
- arrays - Postgre drop bytea[] 列需要很长时间
- python - Pandas 使用 for 循环创建多个数据帧
- goto - Halcon - Goto 语句
- eclipse - 是否可以在没有 Visual Studio 的情况下从 azure dev ops 中的手动套件触发自动化测试套件/计划
- java - 在线程“main”中获取异常 java.util.InputMismatchException