2018 更新: Apollo Client 2.1 添加了一个新的 Mutation 组件,可重新添加加载属性。请参阅下面 @robin-wieruch 的回答和此处的公告 https://dev-blog.apollodata.com/introducing-react-apollo-2-1-c837cc23d926继续阅读原始问题,该问题现在仅适用于 Apollo 的早期版本。
<小时/>使用react-apollo
中当前版本的graphql
高阶组件(v0.5.2),我没有看到有记录的方法来通知我的 UI 突变正在等待服务器响应。我可以看到earlier versions of the package将发送一个指示加载的属性。
查询仍会收到加载属性,如下所示:http://dev.apollodata.com/react/queries.html#default-result-props
我的应用程序也在使用 redux,所以我认为一种方法是将我的组件连接到 redux 并传递一个函数属性,该属性将使我的 UI 进入加载状态。然后,当将我的 graphql 突变重写为属性时,我可以调用来更新 redux 存储。
大致是这样的:
function Form({ handleSubmit, loading, handleChange, value }) {
return (
<form onSubmit={handleSubmit}>
<input
name="something"
value={value}
onChange={handleChange}
disabled={loading}
/>
<button type="submit" disabled={loading}>
{loading ? 'Loading...' : 'Submit'}
</button>
</form>
);
}
const withSubmit = graphql(
gql`
mutation submit($something : String) {
submit(something : $something) {
id
something
}
}
`,
{
props: ({ ownProps, mutate }) => ({
async handleSubmit() {
ownProps.setLoading(true);
try {
const result = await mutate();
} catch (err) {
// @todo handle error here
}
ownProps.setLoading(false);
},
}),
}
);
const withLoading = connect(
(state) => ({ loading: state.loading }),
(dispatch) => ({
setLoading(loading) {
dispatch(loadingAction(loading));
},
})
);
export default withLoading(withSubmit(Form));
我很好奇是否有更惯用的方法来通知用户界面突变正在“进行中”。谢谢。
最佳答案
从Apollo Client 2.1开始,任何偶然发现这个问题的人您可以在查询和修改 component's render props function 中访问这些属性.
import React from "react";
import { Mutation } from "react-apollo";
import gql from "graphql-tag";
const TOGGLE_TODO = gql`
mutation ToggleTodo($id: Int!) {
toggleTodo(id: $id) {
id
completed
}
}
`;
const Todo = ({ id, text }) => (
<Mutation mutation={TOGGLE_TODO} variables={{ id }}>
{(toggleTodo, { loading, error, data }) => (
<div>
<p onClick={toggleTodo}>
{text}
</p>
{loading && <p>Loading...</p>}
{error && <p>Error :( Please try again</p>}
</div>
)}
</Mutation>
);
注意:示例代码取自 Apollo Client 2.1 发布博客文章。
关于reactjs - 如何使用react-apollo graphql确定突变加载状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39379943/