【问题标题】:How to forward data to next page with Apollo and NextJS如何使用 Apollo 和 NextJS 将数据转发到下一页
【发布时间】: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


    【解决方案1】:

    使用 apollo-client 缓存会导致一些问题,这些问题实际上取决于 apollo-client 的实现和 nextjs 的实现。 如果您通过在浏览器地址栏中输入 url 打开应用,Next.js 将从服务器端发出请求(假设视图需要获取数据),然后将呈现的 HTML 发送给客户端。

    因为apollo-client fetch 然后从服务器端缓存数据,那么问题是“Next.js 是否将带有缓存的 apollo-client 发送到客户端以进行下一个请求?” p>

    • 除非你清楚地了解Next.jsapollo-client cache(关于它的实现或它的内部工作原理,如果apollo 在服务器端将数据缓存在内存中,你将失败如果你往这边走)

    • 答案是不确定,因为它同时依赖于两个东西。未来可能会改变!

    所以处理这个问题,就用Next.js的方式,它为数据设计了一个隧道,就是url上的query

    const NameForm = props => {
        const [name, setName] = useState("");
        const client = useApolloClient();
        const router = useRouter();
    
        const handleSubmit = e => {
            e.preventDefault();
            if(!name) return;
            router.push(`/user/register?name=${name}`);
        }
        //render ...
    }
    
    
    import { useRouter } from 'next/router';
    import AddUserForm from '../../components/forms/AddUserForm';
    const AddUser = () => {
        const router = useRouter();
        return (
            <React.Fragment>
                <AddUserForm name={router.query.name} />
            </React.Fragment>
        )
    }
    export default AddUser;
    

    如果你想发送一个对象而不是一个字符串?

    const data = { name: "FoxeyeRinx", email: "foxeye.rinx@gmail.com" };
    const base64 = btoa(JSON.stringify(data));
    router.push(`/user/register?data=${base64}`);
    
    const AddUser = () => {
        const router = useRouter();
        const base64 = router.query.data;
        //decode base64 then parse it to js object
        const data = JSON.parse(atob(base64)); 
        return (
            <React.Fragment>
                <AddUserForm data={data}/>
            </React.Fragment>
        )
    }
    

    如果您认为查询很难看并想隐藏查询,请使用本指南:https://nextjs.org/learn/basics/clean-urls-with-dynamic-routing

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 2022-10-15
      • 2021-11-29
      • 1970-01-01
      • 2021-11-10
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      相关资源
      最近更新 更多