【发布时间】:2020-07-09 21:49:37
【问题描述】:
我正在使用 NextJS、Apollo 和 React(钩子)开发一个 Web 应用程序。
我有一个表单,在注册过程的第一步中询问访问者的姓名。 提交表单时,名称将保存在 Apollo 缓存中,访问者将被重定向到下一页。
import React, { useState } from 'react';
import Router , {useRouter} from 'next/router';
import { useApolloClient } from '@apollo/react-hooks';
const NameForm = props => {
const [name, setName] = useState("");
const client = useApolloClient();
const router = useRouter();
const handleSubmit = e => {
e.preventDefault();
if(!name) return;
client.writeData({ data: { name } });
router.push('/user/register');
}
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Naam</label>
<div>
<input type="text" id="name" name="name" value={name} onChange={e => setName(e.target.value)} />
<button type="submit" onClick={handleSubmit}>Get started</button>
</div>
</div>
</form>
)
}
export default NameForm;
下一页包含更广泛的表格。当访问者来自主页时,该名称是已知的,我想从缓存中取回它。我以为
import { gql } from 'apollo-boost';
import { useApolloClient } from '@apollo/react-hooks';
import AddUserForm from '../../components/forms/AddUserForm';
const GET_NAME = gql`
query GetName {
name @client
}`;
const AddUser = ({ name }) => (
<React.Fragment>
<AddUserForm name={name} />
</React.Fragment>
)
AddUser.getInitialProps = async ctx => {
const client = useApolloClient();
const name = await client.cache.readQuery({ query: GET_NAME });
return { name: name || '' };
}
export default AddUser;
我认为我可以在 getInititialProps 中执行此操作,挂钩只允许在功能组件的主体中使用。
由于 next、react hooks 和 apollo 的不断发展,我缺少有关此的教程/课程,并且我发现很难找到正确的方法来做到这一点。
希望这里有人可以进一步帮助我。
【问题讨论】:
标签: react-hooks next.js apollo apollo-client