【发布时间】:2019-02-18 09:14:16
【问题描述】:
我有一个标头,可以在显示Login/Signup 链接和Logout 状态之间切换,具体取决于它是否可以查询用户对象(基本上表明标头中是否有 jwt)。
这是我卡住的地方:在页面加载时,Header 组件获取用户信息,如果它不返回数据,那么我知道要显示Login/Signup 链接。
所以,我点击登录链接,填写表格并成功登录。我想要发生的是触发 Header 重新获取用户信息。理想情况下,它会从登录返回的用户信息中检查本地缓存。
我已经习惯了 Redux 的思维框架,所以我觉得我缺少一些关于 Apollo 状态管理的基本知识。
以下是代码示例: Header.js
const USER_QUERY = gql`
{
user {
id
email
}
}
`;
const LOGOUT_MUTATION = gql`
mutation LogoutMutation {
logout {
message
}
}
`;
const Header = () => (
<div className="header">
header
<Query query={USER_QUERY}>
{({ loading, error, data }) => {
if (loading) return <div>Fetching</div>;
if (error) {
return (
<div>
<Link to="signup">Signup</Link>
<Link to="login">Login</Link>
</div>
);
}
return (
<div>
{data.user.email}
<Mutation
mutation={LOGOUT_MUTATION}
>
{
mutation => <button type="submit" onClick={mutation}>Logout</button>
}
</Mutation>
</div>
);
}}
</Query>
</div>
);
Auth.js
const SIGNUP_MUTATION = gql`
mutation SignupMutation($name: String!, $email: String!, $password: String!) {
signup(name: $name, email: $email, password: $password) {
id
name
email
}
}
`;
const LOGIN_MUTATION = gql`
mutation LoginMutation($email: String!, $password: String!) {
login(email: $email, password: $password) {
id
name
email
}
}
`;
class Auth extends PureComponent {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
name: '',
isSignup: props.type === 'SIGNUP',
};
}
render() {
const {
email,
password,
name,
isSignup,
} = this.state;
return (
<div>
<h1>{isSignup ? 'Sign Up' : 'Log In'}</h1>
<Mutation
mutation={isSignup ? SIGNUP_MUTATION : LOGIN_MUTATION}
variables={isSignup ? { name, email, password } : { email, password }}
onCompleted={(res) => { console.log('complete', res); }}
>
{
(mutation, { error }) => (
<form
onSubmit={(e) => {
e.preventDefault();
mutation();
}}
>
{
isSignup
&& (
<React.Fragment>
<label htmlFor="auth-name">name</label>
<input
value={name}
onChange={e => this.setState({ name: e.target.value })}
type="text"
placeholder="name"
id="auth-name"
/>
</React.Fragment>
)
}
<label htmlFor="email">email</label>
<input
value={email}
onChange={e => this.setState({ email: e.target.value })}
type="text"
placeholder="email"
id="auth-email"
/>
<label htmlFor="password">password</label>
<input
value={password}
onChange={e => this.setState({ password: e.target.value })}
type="password"
placeholder="password"
id="auth-password"
/>
<button type="submit">Submit</button>
{ error && <div>ERROR Authenticating</div>}
</form>
)
}
</Mutation>
</div>
);
}
}
【问题讨论】:
标签: reactjs graphql apollo apollo-client