【发布时间】:2020-06-05 08:45:40
【问题描述】:
如何处理useMutation 的错误,以免页面变成令人不快的Unhandled Rejection (Error)?
虽然here 这个帖子描述了我的问题,但我仍然无法解决它。帖子特别提到。 Instead of having to write the above boilerplate yourself, you can just use the provided result object. 我是这样做的:
const [signUp, { loading: mutationLoading, error: mutationError } [...]
但是,当发生错误时,我的 React 应用程序总是切换到一个不好的“未处理的拒绝(错误):GraphQL 错误”屏幕。类似的解决方案似乎在 official doc 中有效——但不适用于我。
function SignUp() {
// Declare a new state variable, which we'll call "count"
const [login, setLogin] = useState(true);
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [name, setName] = useState("");
const [
signUp,
{ loading: mutationLoading, error: mutationError }
] = useMutation(SIGNUP_MUTATION, {
onCompleted(data) {
const { token } = login ? data.tokenAuth : data.createUser;
localStorage.setItem(AUTH_TOKEN, token);
console.log(token);
// this.props.history.push(`/`);
}
});
return (
<div>
{mutationLoading && <p>Loading...</p>}
{mutationError && (
<p>
Some error occured :(
{console.log(mutationError)}
{mutationError.graphQLErrors.map(({ message }, i) => (
<span key={i}>{message}</span>
))}
</p>
)}
[...]
【问题讨论】:
-
我写道:“当您希望 UI 反映存在错误的事实时,具有这样的错误状态可能很有用。例如,您可以更改元素,直到突变运行没有错误。您不必自己编写上述样板,只需使用提供的结果对象即可。”
-
error对象是为了方便操作 UI 而公开的。它不能替代使用 1)catch或 2)onError或 3) 使用 ErrorLink 并从响应中删除错误来实际处理错误。 -
谢谢丹尼尔的回答。你给我一个我的代码示例 1)我无法使用该示例创建一个工作版本
-
signUp.catch(e => /* do something with the error */)
标签: reactjs apollo react-apollo apollo-client