翻译 | 《JavaScript Everywhere》第16章 创建,读取,更新和删除操作

Cursor实战指南:Next.js+Supabase项目中的AI副驾驶用法 AI编程助手已从代码补全工具演进为具备项目级上下文理解能力的工程协作者。其核心价值在于深度解析TypeScript类型契约、跨文件语义关联与错误驱动式调试闭环,尤其适用于Next.js App Router与Supabase等现代全栈技术栈的快速交付场景。通过显式提示词工程、RLS策略生成、自动化测试覆盖及Code-as-Doc文档同步等实践,开发者可在真实项目中将Cursor定位为‘可信赖的副驾驶’——既提升开发效率,又强化架构一致性与边界条件把控能力。 阅读详情

翻译 | 《JavaScript Everywhere》第16章 创建,读取,更新和删除操作

写在最前面

大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。

为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。

(σ゚∀゚)σ…:*☆哎哟不错哦

第16章 创建,读取,更新和删除操作

我喜欢纸质笔记本,几乎一直都随身携带着。通常,它们相对便宜,我很快就写满了临时的想法。不久前,我购买了价格更高的精装本笔记本,上面有精美的封面和精美的纸本。购买时,我对笔记本中将要出现的草图和计划抱有很大的野心,但是它在我的办公桌上呆了几个月。最终,我将其放在架子上,回到了我的标准笔记本电脑品牌。

就像我的笔记本一样,我们的应用仅在用户能够使用时才有用。你可能会从我们的API开发中回想起Notedly应用程序是一个“ CRUD”(创建,读取,更新和删除)应用程序。经过身份验证的用户可以创建新笔记、阅读笔记、更新笔记的内容或笔记作为收藏夹的状态以及删除笔记。在本章中,我们将在Web用户界面中实现所有这些功能。为了完成这些任务,我们将编写GraphQL请求和查询。

创建新笔记

当前,我们可以查看笔记,但无法创建笔记。这类似于没有笔的笔记本。让我们为用户添加创建新笔记的功能。我们将通过创建一个用户可以在其中写笔记的textarea形式。

当用户提交表单时,我们将执行GraphQL更改以在数据库中创建笔记。

首先,让我们在src/pages/new.js中创建NewNote组件:

import React, { useEffect } from 'react';
import { useMutation, gql } from '@apollo/client';

const NewNote = props => {
  useEffect(() => {
   // update the document title
   document.title = 'New Note — Notedly';
  });

  return <div>New note</div>;
};

export default NewNote; 

接下来,让我们在src/pages/index.js文件中设置新路由:

// import the NewNote route component
import NewNote from './new';

// add a private route to our list of routes, within the
<PrivateRoute path="/new" component={NewNote} /> 

我们知道,我们将创建新笔记并更新现有笔记。为了适应这种行为,让我们创建一个名为NoteForm的新组件,该组件将用作笔记表单编辑的标记和React状态。

我们将在src/components/NoteForm.js中创建一个新文件。该组件将由一个包含文本区域以及一些最小样式的表单元素组成。该功能将非常类似于我们的UserForm组件:

import React, { useState } from 'react';
import styled from 'styled-components';

import Button from './Button';

const Wrapper = styled.div`
  height: 100%;
`;

const Form = styled.form`
  height: 100%;
`;

const TextArea = styled.textarea`
  width: 100%;
  height: 90%;
`;

const NoteForm = props => {
  // set the default state of the form
  const [value, setValue] = useState({ content: props.content || '' });

  // update the state when a user types in the form
  const onChange = event => {
   setValue({
    ...value,
    [event.target.name]: event.target.value
   });
  };

  return (
   <Wrapper> <Form onSubmit={e => {
      e.preventDefault();
      props.action({
       variables: {
        ...values
       }
      });
     }}
    > <TextArea required type="text" name="content" placeholder="Note content" value={value.content} onChange={onChange} /> <Button type="submit">Save</Button> </Form> </Wrapper> );
};

export default NoteForm; 

下一步,我们将需要参考在NewNote页面组件的NoteForm成分。在src/pages/new.js中:

 import React, { useEffect } from 'react';
import { useMutation, gql } from '@apollo/client';
// import the NoteForm component
import NoteForm from '../components/NoteForm';

const NewNote = props => {
  useEffect(() => {
   // update the document title
   document.title = 'New Note — Notedly';
  });

  return <NoteForm />;
};
export default NewNote; 

有了这些更新,切换至http://localhost:1234/new将显示我们的效果(图16-1)。

图16-1我们的NewNote组件为用户提供了一个较大的文本区域和保存按钮

完成表格后,我们可以开始编写我们的修改以创建新笔记。

在src/pages/new.js中:

 import React, { useEffect } from 'react';
import { useMutation, gql } from '@apollo/client';

import NoteForm from '../components/NoteForm';

// our new note query
const NEW_NOTE = gql`
  mutation newNote($content: String!) {
   newNote(content: $content) {
    id
    content
    createdAt
    favoriteCount
    favoritedBy {
     id
     username
    }
    author {
     username
     id
    }
   }
  }
`;

const NewNote = props => {
  useEffect(() => {
   // update the document title
   document.title = 'New Note — Notedly';
  });

  const [data, { loading, error }] = useMutation(NEW_NOTE, {
   onCompleted: data => {
    // when complete, redirect the user to the note page
    props.history.push(`note/${data.newNote.id}`);
   }
  });

  return (
   <React.Fragment>
    {/* as the mutation is loading, display a loading message*/}
    {loading && <p>Loading...</p>}
    {/* if there is an error, display a error message*/}
    {error && <p>Error saving the note</p>}
    {/* the form component, passing the mutation data as a prop */}
    <NoteForm action={data} />
   </React.Fragment>
  );
};

export default NewNote; 

在前面的代码中,提交表单时,我们执行newNote修改。如果修改成功,则将用户重定向到单个笔记页面。你可能会注意到newNote修改请求了很多数据。这与笔记修改所请求的数据匹配,理想地更新了Apollo的缓存以快速切换到各个笔记组件。

如前所述,Apollo积极地缓存我们的查询,这有助于加快应用程序的切换。不幸的是,这也意味着用户可以访问页面,而看不到他们刚刚进行的更新。我们可以手动更新Apollo的缓存,但是更简单的方法是使用Apollo的refetchQueries功能可在执行修改时有意地更新缓存。

为此,我们需要访问预先编写的查询。到目前为止,我们一直将它们包含在组件文件的顶部,但让我们将其移动到自己的query.js文件中。在/src/gql/query.js中创建一个新文件,并添加我们的每个笔记查询以及IS\_LOGGED\_IN查询:

import { gql } from '@apollo/client';

const GET_NOTES = gql`
  query noteFeed($cursor: String) {
   noteFeed(cursor: $cursor) {
    cursor
    hasNextPage
    notes {
     id
     createdAt
     content
     favoriteCount
     author {
      username
      id
      avatar
     }
    }
   }
  }
`;

const GET_NOTE = gql`
  query note($id: ID!) {
   note(id: $id) {
    id
    createdAt
    content
    favoriteCount
    author {
     username
     id
     avatar
    }
   }
  }
`;

const IS_LOGGED_IN = gql`
  {
   isLoggedIn @client
  }
`;

export { GET_NOTES, GET_NOTE, IS_LOGGED_IN };

可重用的查询和修改

展望未来,我们将所有查询和修改都与组件分开,这将使我们能够轻松地在应用程序中重用它们,并且对于在测试期间mocking。

现在在src/pages/new.js中,我们可以通过导入查询并添加refetchQueries选项来请求我们的修改重新获取GET\_NOTES查询:

// import the query
import { GET_NOTES } from '../gql/query';

// within the NewNote component update the mutation
//everything else stays the same

const NewNote = props => {
  useEffect(() => {
   // update the document title
   document.title = 'New Note — Notedly';
  });

  const [data, { loading, error }] = useMutation(NEW_NOTE, {
   // refetch the GET_NOTES query to update the cache
   refetchQueries: [{ query: GET_NOTES }],
   onCompleted: data => {
    // when complete, redirect the user to the note page
    props.history.push(`note/${data.newNote.id}`);
   }
  });

  return (
   <React.Fragment>
    {/* as the mutation is loading, display a loading message*/}
    {loading && <p>Loading...</p>}
    {/* if there is an error, display a error message*/}
    {error && <p>Error saving the note</p>}
    {/* the form component, passing the mutation data as a prop */}
    <NoteForm action={data} />
   </React.Fragment>
  );
}; 

我们的最后一步是将链接添加到我们的/new页面,以便用户可以轻松切换到该页面。在src/components/Navigation.js文件中,添加一个新的链接项,如下所示:

<li>
  <Link to="/new">New</Link>
</li> 

这样,我们的用户就可以切换到新的笔记页面,输入笔记,然后将笔记保存到数据库中。

阅读用户说明

我们的应用程序当前能够读取我们的笔记摘要以及单个笔记,但是我们还没有查询经过身份验证的用户的笔记。让我们编写两个GraphQL查询来创建用户及其收藏夹的提要。

在src/gql/query.js中,添加GET\_MY\_NOTES查询并更新导出,如下所示:

// add the GET_MY_NOTES query
const GET_MY_NOTES = gql`
  query me {
    me {
      id
      username
      notes {
        id
        createdAt
        content
        favoriteCount
        author {
          username
          id
          avatar
        }
      }
    }
  }
`;

// update to include GET_MY_NOTES
export { GET_NOTES, GET_NOTE, IS_LOGGED_IN, GET_MY_NOTES }; 

现在在src/pages/mynotes.js中,导入查询并使用NoteFeed组件显示笔记:

import React, { useEffect } from 'react';
import { useQuery, gql } from '@apollo/client';

import NoteFeed from '../components/NoteFeed';
import { GET_MY_NOTES } from '../gql/query';

const MyNotes = () => {
  useEffect(() => {
    // update the document title
    document.title = 'My Notes — Notedly';
  });

  const { loading, error, data } = useQuery(GET_MY_NOTES);

  // if the data is loading, our app will display a loading message
  if (loading) return 'Loading...';
  // if there is an error fetching the data, display an error message
  if (error) return `Error! ${error.message}`;
  // if the query is successful and there are notes, return the feed of notes
  // else if the query is successful and there aren't notes, display a message
  if (data.me.notes.length !== 0) {
    return <NoteFeed notes={data.me.notes} />;
  } else {
    return <p>No notes yet</p>;
  }
};

export default MyNotes; 

我们可以重复此过程以创建“收藏夹”页面。首先,在src/gql/query.js中:

 // add the GET_MY_FAVORITES query
const GET_MY_FAVORITES = gql`
  query me {
    me {
      id
      username
      favorites {
        id
        createdAt
        content
        favoriteCount
        author {
          username
          id
          avatar
        }
      }
    }
  }
`;

// update to include GET_MY_FAVORITES
export { GET_NOTES, GET_NOTE, IS_LOGGED_IN, GET_MY_NOTES, GET_MY_FAVORITES }; 

现在,在src/pages/favorites.js中:

import React, { useEffect } from 'react';
import { useQuery, gql } from '@apollo/client';

import NoteFeed from '../components/NoteFeed';
// import the query
import { GET_MY_FAVORITES } from '../gql/query';

const Favorites = () => {
  useEffect(() => {
    // update the document title
    document.title = 'Favorites — Notedly';
  });

  const { loading, error, data } = useQuery(GET_MY_FAVORITES);

  // if the data is loading, our app will display a loading message
  if (loading) return 'Loading...';
  // if there is an error fetching the data, display an error message
  if (error) return `Error! ${error.message}`;
  // if the query is successful and there are notes, return the feed of notes
  // else if the query is successful and there aren't notes, display a message
  if (data.me.favorites.length !== 0) {
    return <NoteFeed notes={data.me.favorites} />;
  } else {
    return <p>No favorites yet</p>;
  }
};

export default Favorites; 

最后,让我们更新src/pages/new.js文件以重新获取GET\_MY\_NOTES查询,以确保在创建笔记时更新了用户笔记的缓存列表。在src/pages/new.js中,首先更新GraphQL查询import语句:

import { GET_MY_NOTES, GET_NOTES } from '../gql/query'; 

然后更新修改:

const [data, { loading, error }] = useMutation(NEW_NOTE, {
  // refetch the GET_NOTES and GET_MY_NOTES queries to update the cache
  refetchQueries: [{ query: GET_MY_NOTES }, { query: GET_NOTES }],
  onCompleted: data => {
    // when complete, redirect the user to the note page
    props.history.push(`note/${data.newNote.id}`);
  }
}); 

通过这些更改,我们现在可以在我们的应用程序中执行所有读取操作。

更新说明

当前,用户一旦写了笔记,便无法对其进行更新。为了解决这个问题,我们希望在应用程序中启用笔记编辑。我们的GraphQL API具有updateNote修改,它接受笔记ID和内容作为参数。如果笔记存在于数据库中,则修改将使用修改中发送的内容更新存储的内容。

在我们的应用程序中,我们可以在/ edit/NOTE\_ID处创建一条路由,将现有笔记内容放置在textarea表单中。当用户单击“保存”时,我们将提交表单并执行updateNote更改。

让我们创建一条新路由,在该路由中将编辑我们的笔记。首先,我们可以使我们的一个重复的src/pages/ note.js页并将其命名为edit.js。目前,该页面仅显示笔记。

在src/pages/edit.js中:

import React from 'react';
import { useQuery, useMutation, gql } from '@apollo/client';

// import the Note component
import Note from '../components/Note';
// import the GET_NOTE query
import { GET_NOTE } from '../gql/query';

const EditNote = props => {
  // store the id found in the url as a variable
  const id = props.match.params.id;
  // define our note query
  const { loading, error, data } = useQuery(GET_NOTE, { variables: { id } });

  // if the data is loading, display a loading message
  if (loading) return 'Loading...';
  // if there is an error fetching the data, display an error message
  if (error) return <p>Error! Note not found</p>;
  // if successful, pass the data to the note component
  return <Note note={data.note} />;
};

export default EditNote; 

现在,我们可以通过将页面添加到src/pages/index.js中的路由来使页面可切换:

// import the edit page component
import EditNote from './edit';

// add a new private route that accepts an :id parameter
<PrivateRoute path="/edit/:id" component={EditNote} /> 

这样,如果你切换到/note/ID处的笔记页面并将其交换为/edit/ID,你将看到笔记的改变。让我们对其进行更改,以使其显示在表单的textarea中显示的笔记内容。

在src/pages/edit.js中,删除Note组件的import语句,并将其替换为NoteForm组件:

// import the NoteForm component
import NoteForm from '../components/NoteForm'; 

现在,我们可以更新EditNote组件来使用我们的编辑表单。我们可以使用content属性将笔记的内容传递给表单组件。虽然我们的GraphQL修改仅接受原作者的更新,但我们也可以只将表单显示的范围限制为笔记的作者,以避免混淆其他用户。

首先,将新查询添加到src/gql/query.js文件中,以获取当前用户,其用户ID以及收藏的笔记ID的列表:

// add GET_ME to our queries
const GET_ME = gql`
  query me {
    me {
      id
      favorites {
        id
      }
    }
  }
`;

// update to include GET_ME
export {
  GET_NOTES,
  GET_NOTE,
  GET_MY_NOTES,
  GET_MY_FAVORITES,
  GET_ME,
  IS_LOGGED_IN
}; 

在src/pages/edit.js中,导入GET\_ME查询并包括用户检查:

import React from 'react';
import { useMutation, useQuery } from '@apollo/client';

// import the NoteForm component
import NoteForm from '../components/NoteForm';
import { GET_NOTE, GET_ME } from '../gql/query';
import { EDIT_NOTE } from '../gql/mutation';

const EditNote = props => {
  // store the id found in the url as a variable
  const id = props.match.params.id;
  // define our note query
  const { loading, error, data } = useQuery(GET_NOTE, { variables: { id } });
  // fetch the current user's data
  const { data: userdata } = useQuery(GET_ME);
  // if the data is loading, display a loading message
  if (loading) return 'Loading...';
  // if there is an error fetching the data, display an error message
  if (error) return <p>Error! Note not found</p>;
  // if the current user and the author of the note do not match
  if (userdata.me.id !== data.note.author.id) {
    return <p>You do not have access to edit this note</p>;
  }
  // pass the data to the form component
  return <NoteForm content={data.note.content} />;
}; 

现在,我们可以编辑表单中的笔记,但是单击按钮尚不能保存我们的更改。让我们写我们的GraphQLupdateNote修改。与查询文件类似,让我们创建一个文件来保存我们的修改。在src/gql/mutation中,添加以下内容:

import { gql } from '@apollo/client';

const EDIT_NOTE = gql`
  mutation updateNote($id: ID!, $content: String!) {
    updateNote(id: $id, content: $content) {
      id
      content
      createdAt
      favoriteCount
      favoritedBy {
        id
        username
      }
      author {
        username
        id
      }
    }
  }
`;

export { EDIT_NOTE }; 

编写好修改后,我们可以导入它并更新我们的组件代码,以在单击按钮时调用该修改。为此,我们将添加一个useMutation挂钩。修改完成后,我们会将用户重定向到笔记页面。

// import the mutation
import { EDIT_NOTE } from '../gql/mutation';

const EditNote = props => {
  // store the id found in the url as a variable
  const id = props.match.params.id;
  // define our note query
  const { loading, error, data } = useQuery(GET_NOTE, { variables: { id } });
  // fetch the current user's data
  const { data: userdata } = useQuery(GET_ME);
  // define our mutation
  const [editNote] = useMutation(EDIT_NOTE, {
    variables: {
      id
    },
    onCompleted: () => {
      props.history.push(`/note/${id}`);
    }
  });

  // if the data is loading, display a loading message
  if (loading) return 'Loading...';
  // if there is an error fetching the data, display an error message
  if (error) return <p>Error!</p>;
  // if the current user and the author of the note do not match
  if (userdata.me.id !== data.note.author.id) {
    return <p>You do not have access to edit this note</p>;
  }

  // pass the data and mutation to the form component
  return <NoteForm content={data.note.content} action={editNote} />;
};

export default EditNote; 

最后,我们只想向用户显示“编辑”链接,但前提是用户是笔记的作者。在我们的应用程序中,我们将需要检查以确保当前用户的ID与笔记作者的ID相匹配。为了实现此行为,我们将涉及几个组件。

现在,我们可以直接在Note组件中实现我们的功能,让我们在src/components/NoteUser.js上创建一个专门用于登录用户交互的组件。在这个React组件中,我们将对当前用户ID执行GraphQL查询,并提供一个指向编辑页面的可路由链接。有了这些信息,我们就可以开始导入所需的库并设置一个新的React组件。在React组件内,我们将包含一个编辑链接,该链接会将用户引导至笔记的编辑页面。现在,无论笔记的所有者是谁,用户都将看到此链接。

如下更新src/components/NoteUser.js:

import React from 'react';
import { useQuery, gql } from '@apollo/client';
import { Link } from 'react-router-dom';

const NoteUser = props => {
  return <Link to={`/edit/${props.note.id}`}>Edit</Link>;
};

export default NoteUser; 

接下来,我们将更新Note组件以执行本地isLoggedIn状态查询。

然后,我们可以根据用户的登录状态有条件地呈现NoteUser组件。

首先,我们导入GraphQL库与NoteUser组件一起执行查询。在src/components/Note.js中,在文件顶部添加以下内容:

import { useQuery } from '@apollo/client';

// import logged in user UI components
import NoteUser from './NoteUser';
// import the IS_LOGGED_IN local query
import { IS_LOGGED_IN } from '../gql/query'; 

现在,我们可以更新我们的JSX组件以检查登录状态。如果用户已登录,我们将显示NoteUser组件;否则,我们将显示收藏夹计数。

const Note = ({ note }) => {
  const { loading, error, data } = useQuery(IS_LOGGED_IN);
  // if the data is loading, display a loading message
  if (loading) return <p>Loading...</p>;
  // if there is an error fetching the data, display an error message
  if (error) return <p>Error!</p>;

  return (
    <StyledNote>
      <MetaData>
        <MetaInfo>
          <img src={note.author.avatar} alt={`${note.author.username} avatar`} height="50px" />
        </MetaInfo>
        <MetaInfo>
          <em>by</em> {note.author.username} <br />
          {format(note.createdAt, 'MMM Do YYYY')}
        </MetaInfo>
        {data.isLoggedIn ? (
          <UserActions>
            <NoteUser note={note} />
          </UserActions>
        ) : (
          <UserActions>
            <em>Favorites:</em> {note.favoriteCount}
          </UserActions>
        )}
      </MetaData>
      <ReactMarkdown source={note.content} />
    </StyledNote>
  );
}; 

未经身份验证的编辑

尽管我们将在UI中隐藏编辑链接,但用户仍然可以切换到笔记的编辑屏幕,而无需成为笔记所有者。值得庆幸的是,我们的GraphQL API旨在防止笔记所有者以外的任何人编辑笔记的内容。我们不会在本书中进行介绍,但是一个不错的附加步骤是更新src/pages/edit.js组件以重定向用户(如果他们不是笔记所有者)。

进行此更改后,登录用户可以在每个笔记的顶部看到一个编辑链接。单击该链接将切换到一个编辑表单,而不管笔记的所有者是谁。让我们通过更新NoteUser组件来查询当前用户的ID并仅在其与笔记作者的ID匹配时显示编辑链接来解决此问题。

首先在src/components/NoteUser.js中,添加以下内容:

import React from 'react'; import { useQuery } from '@apollo/client'; import { Link } from 'react-router-dom'; // import our GET_ME query
import { GET_ME } from '../gql/query'; const NoteUser = props => { const { loading, error, data } = useQuery(GET_ME); // if the data is loading, display a loading message
  if (loading) return <p>Loading...</p>; // if there is an error fetching the data, display an error message
  if (error) return <p>Error!</p>; return (
    <React.Fragment>
      Favorites: {props.note.favoriteCount}
      <br />
      {data.me.id === props.note.author.id && (
        <React.Fragment>
          <Link to={`/edit/${props.note.id}`}>Edit</Link>
        </React.Fragment>
      )}
    </React.Fragment>
  );
};

export default NoteUser; 

进行此更改后,只有笔记的原始作者才能在UI中看到编辑链接(图16-2)。

图16-2。只有笔记的作者才能看到编辑链接

删除笔记

我们的CRUD应用程序仍然缺少删除笔记的功能。我们可以编写一个UI按钮组件,单击该组件将执行GraphQL修改,从而删除笔记。让我们从src/components/DeleteNote.js创建一个新组件开始。由于我们将在不可路由的组件内执行重定向,因此我们将使用React Router的withRouter高阶组件:

import React from 'react';
import { useMutation } from '@apollo/client';
import { withRouter } from 'react-router-dom';

import ButtonAsLink from './ButtonAsLink';

const DeleteNote = props => {
  return <ButtonAsLink>Delete Note</ButtonAsLink>;
};

export default withRouter(DeleteNote); 

现在,我们可以编写我们的修改了。我们的GraphQL API具有deleteNote修改,如果删除了笔记,则返回布尔值true。修改完成后,我们会将用户重定向到应用程序的/ mynotes页面。

首先,在src/gql/mutation.js中,按如下所示编写修改:

const DELETE_NOTE = gql`
  mutation deleteNote($id: ID!) {
    deleteNote(id: $id)
  }
`;

// update to include DELETE_NOTE
export { EDIT_NOTE, DELETE_NOTE }; 

现在在src/components/DeleteNote中,添加以下内容:

import React from 'react';
import { useMutation } from '@apollo/client';
import { withRouter } from 'react-router-dom';

import ButtonAsLink from './ButtonAsLink';
// import the DELETE_NOTE mutation
import { DELETE_NOTE } from '../gql/mutation';
// import queries to refetch after note deletion
import { GET_MY_NOTES, GET_NOTES } from '../gql/query';

const DeleteNote = props => {
  const [deleteNote] = useMutation(DELETE_NOTE, {
    variables: {
      id: props.noteId
    },
    // refetch the note list queries to update the cache
    refetchQueries: [{ query: GET_MY_NOTES, GET_NOTES }],
    onCompleted: data => {
      // redirect the user to the "my notes" page
      props.history.push('/mynotes');
    }
  });

  return <ButtonAsLink onClick={deleteNote}>Delete Note</ButtonAsLink>;
};

export default withRouter(DeleteNote); 

现在,我们可以在src/components/NoteUser.js文件中导入新的DeleteNote组件,仅将其显示给笔记的作者:

import React from 'react';
import { useQuery } from '@apollo/client';
import { Link } from 'react-router-dom';

import { GET_ME } from '../gql/query';
// import the DeleteNote component
import DeleteNote from './DeleteNote';

const NoteUser = props => {
  const { loading, error, data } = useQuery(GET_ME);
  // if the data is loading, display a loading message
  if (loading) return <p>Loading...</p>;
  // if there is an error fetching the data, display an error message
  if (error) return <p>Error!</p>;

  return (
    <React.Fragment>
      Favorites: {props.note.favoriteCount} <br />
      {data.me.id === props.note.author.id && (
        <React.Fragment>
          <Link to={`/edit/${props.note.id}`}>Edit</Link> <br />
          <DeleteNote noteId={props.note.id} />
        </React.Fragment>
      )}
    </React.Fragment>
  );
};

export default NoteUser; 

写入此修改后,登录用户现在可以通过单击按钮删除笔记。

切换收藏夹

我们的应用程序缺少的最后一个用户功能是能够添加和删除“收藏夹”笔记。让我们遵循为该功能创建组件并将其集成到我们的应用程序中的模式。首先,在src/components/FavoriteNote.js中创建一个新组件:

import React, { useState } from 'react';
import { useMutation } from '@apollo/client';

import ButtonAsLink from './ButtonAsLink';

const FavoriteNote = props => {
  return <ButtonAsLink>Add to favorites</ButtonAsLink>;
};

export default FavoriteNote; 

在添加任何功能之前,让我们继续将该组件合并到我们的src/components/NoteUser.js组件中。首先,导入组件:

import FavoriteNote from './FavoriteNote'; 

现在,在我们的JSX中,包括了对该组件的引用。你可能还记得,当我们编写GET\_ME查询时,我们包括了一个喜爱的笔记ID列表,我们将在这里使用它:

 return (
  <React.Fragment>
    <FavoriteNote me={data.me} noteId={props.note.id} favoriteCount={props.note.favoriteCount} />
    <br />
    {data.me.id === props.note.author.id && (
      <React.Fragment>
        <Link to={`/edit/${props.note.id}`}>Edit</Link> <br />
        <DeleteNote noteId={props.note.id} />
      </React.Fragment>
    )}
  </React.Fragment>
); 

你会注意到,我们正在将三个属性传递给FavoriteNote组件。首先是我们的我的数据,其中包括当前用户的ID,以及由用户收藏笔记的列表。第二,当前笔记的noteID。最后是favoriteCount,它是当前用户收藏夹的总数。

现在,我们可以返回src/components/FavoriteNote.js文件。在此文件中,我们将存储当前收藏夹数作为状态,并检查当前笔记ID是否在用户收藏夹的现有列表中。我们将根据用户收藏夹的状态更改用户看到的文本。当用户单击按钮时,它将调用我们的toggleFavorite修改,该修改将在用户列表中添加或删除收藏夹。让我们首先更新组件以使用状态来控制点击功能。

const FavoriteNote = props => {
  // store the note's favorite count as state
  const [count, setCount] = useState(props.favoriteCount);

  // store if the user has favorited the note as state
  const [favorited, setFavorited] = useState(
    // check if the note exists in the user favorites list
    props.me.favorites.filter(note => note.id === props.noteId).length > 0
  );

  return (
    <React.Fragment> {favorited ? ( <ButtonAsLink onClick={() => {
            setFavorited(false);
            setCount(count - 1);
          }}
        >
          Remove Favorite </ButtonAsLink> ) : ( <ButtonAsLink onClick={() => {
            setFavorited(true);
            setCount(count + 1);
          }}
        >
          Add Favorite </ButtonAsLink> )}
      : {count} </React.Fragment> );
}; 

通过前面的更改,我们将在用户单击时更新状态,但尚未调用GraphQL修改。让我们通过编写修改并将其添加到组件中来完成此组件。结果显示为图16-3。

在src/gql/mutation.js中:

// add the TOGGLE_FAVORITE mutation
const TOGGLE_FAVORITE = gql`
  mutation toggleFavorite($id: ID!) {
    toggleFavorite(id: $id) {
      id
      favoriteCount
    }
  }
`;

// update to include TOGGLE_FAVORITE
export { EDIT_NOTE, DELETE_NOTE, TOGGLE_FAVORITE }; 

在src/components/FavoriteNote.js中:

import React, { useState } from 'react';
import { useMutation } from '@apollo/client';

import ButtonAsLink from './ButtonAsLink';
// the TOGGLE_FAVORITE mutation
import { TOGGLE_FAVORITE } from '../gql/mutation';
// add the GET_MY_FAVORITES query to refetch
import { GET_MY_FAVORITES } from '../gql/query';

const FavoriteNote = props => {
  // store the note's favorite count as state
  const [count, setCount] = useState(props.favoriteCount);

  // store if the user has favorited the note as state
  const [favorited, setFavorited] = useState(
    // check if the note exists in the user favorites list
    props.me.favorites.filter(note => note.id === props.noteId).length > 0
  );

  // toggleFavorite mutation hook
  const [toggleFavorite] = useMutation(TOGGLE_FAVORITE, {
    variables: {
      id: props.noteId
    },
    // refetch the GET_MY_FAVORITES query to update the cache
    refetchQueries: [{ query: GET_MY_FAVORITES }]
  });

  // if the user has favorited the note, display the option to remove the favorite
  // else, display the option to add as a favorite
  return (
    <React.Fragment> {favorited ? ( <ButtonAsLink onClick={() => {
            toggleFavorite();
            setFavorited(false);
            setCount(count - 1);
          }}
        >
          Remove Favorite </ButtonAsLink> ) : ( <ButtonAsLink onClick={() => {
            toggleFavorite();
            setFavorited(true);
            setCount(count + 1);
          }}
        >
          Add Favorite </ButtonAsLink> )}
      : {count} </React.Fragment> );
};

export default FavoriteNote; 

图16-3。登录的用户将能够创建,阅读,更新和删除笔记

结论

在本章中,我们已将站点变成功能齐全的CRUD(创建,读取,更新,删除)应用程序。现在,我们可以根据已登录用户的状态来实现GraphQL查询和修改。构建集成CRUD用户交互的用户界面的能力将为构建各种Web应用程序奠定坚实的基础。借助此功能,我们已经完成了应用的MVP(最低可行产品)。在下一章中,我们将应用程序部署到Web服务器上。

如果有理解不到位的地方,欢迎大家纠错。如果觉得还可以,麻烦你点赞收藏或者分享一下,希望可以帮到更多人。

AI 工作流和AI Agent构建指南 这些智能体能够自主感知、推理和行动,以追求特定目标,形成强大的集体智慧,可以打破孤岛,集成不同的数据源,并提供无缝的端到端自动化。如今随着AI应用的逐步深化应用和融合发展,一个新的工具应用而生,那就是工作流(Agentic Workflow智能体工作流\代理工作流)或AI agent,它们的结合正在重塑现代企业的运营模式,通过自动化、智能决策和效率优化推动数字化转型。针对这个问题,我们可以通过RAG(检索增强生成)来解决,即通过提供相关的、实时的外部数据来增强 LLM 的响应准确性**,但它仅限于。 阅读详情

相关推荐

翻译 | 《JavaScript Everywhere》第19章 将现有的Web应用程序与Electron集成

翻译 | 《JavaScript Everywhere》第19章 将现有的Web应用程序与Electron集成(_) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ…:*☆哎哟不错哦 第19章 将现有的Web应用程序与Electron集成 我喜欢收集浏览器书签,就像一

前端毛小悠的博客 344

翻译 | 《JavaScript Everywhere》第9章 详细信息(^_^)

翻译 | 《JavaScript Everywhere》第9章 详细信息(_) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ…:*☆哎哟不错哦 第9章 详细信息 当现在普遍存在的空气清新剂Febreze首次发布时,它就像是一个哑巴。 原始的广告只显示人们使用该产品可

前端毛小悠的博客 231

【信息科学与工程学】计算机科学与自动化 第二百三十三篇 凤凰架构02

① Firecracker 为每个 microVM 提供极简设备模型:virtio-net, virtio-blk, serial console。:① BB84:Alice 随机选择基矢(+ 或 ×)发送单光子,Bob 随机测量基矢,比对后保留一致位的子集作为原始密钥。:密度 1 EB/mm³;:① Parquet 文件:行组(Row Group)→ 列块(Column Chunk)→ 页(Page)。

weixin_49199313的博客 138

JavaScript Everywhere API 项目安装与配置指南

JavaScript Everywhere API 项目安装与配置指南 1. 项目基础介绍 JavaScript Everywhere API 是一个开源项目,提供了一系列API代码示例,用于帮助开发者学习如何在全栈JavaScript应用中构建API。该项目主要使用JavaScript语言进行开发。 2. 项目使用的关键技术和框架 Node.js: JavaScript runtime环境,允...

gitblog_00114的博客 814

“傻瓜”学计量——双重差分DID3(多期双重差分原理+解决方案CSDID原理)

“傻瓜”学计量——双重差分DID3(多期双重差分原理+解决方案CSDID原理)

nnpersistent的博客 5062

STM32F103C8T6飞控入门:从零开始,用HAL库和MPU6050搭建你的第一架四轴无人机

本文详细介绍了如何使用STM32F103C8T6和MPU6050模块从零开始搭建四轴无人机飞控系统。通过硬件选型、电路设计、HAL库配置、姿态解算算法实现以及PID控制等步骤,帮助创客和嵌入式爱好者快速入门飞控开发。文章还提供了实用的调试技巧和常见问题解决方案,适合想要掌握四旋翼无人机核心技术的开发者。

weixin_42524750的博客 267

翻译 | 《JavaScript Everywhere》第1章 开发环境(^_^)

翻译 | 《JavaScript Everywhere》第1章 开发环境(^_^) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构略有调整和内容的增删。如果发现本文中有存在瑕疵的地方,或者您有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。(σ゚∀゚)σ..:*☆哎哟不错哦 为无处不在的JavaScript赞美 JavaScript Everywhere 是一本令人难以置信的书,它将为

前端毛小悠的博客 657

Agent 操作系统:未来的 Harness 平台

在大模型技术爆发的当下,自主智能体(Agent)已经成为AI原生应用的核心载体,但当前Agent开发面临着碎片化严重、运维难度高、规模化落地难三大核心痛点,就像1970年代没有通用操作系统的裸机编程时代,开发者需要重复造轮子解决底层基础设施问题。本文将深度解析Agent操作系统(Agent OS)作为AI原生时代的底层基础设施的核心定位,以及下一代Harness平台如何将Agent OS与成熟的DevOps、CI/CD、可观测性、成本管理能力深度融合,成为AI原生应用全生命周期管理的统一平台。

软件工程实践的博客 280

翻译 | 《JavaScript Everywhere》第4章 我们的第一个GraphQL API(^_^)

文章目录写在最前面第4章 我们的第一个GraphQL API将我们的服务器转换为API(排序)注意GraphQL基础查询修改调整我们的API数据存储结论数据存储结论 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ..:*☆哎哟不错哦 第4章 我们的第一个GraphQL

前端毛小悠的博客 553

『言善信』Fiddler工具 — 1、Fiddler介绍与安装

文章目录1、Fiddler简介2、Fiddler功能3、Fiddler工作原理4、Fiddler安装 1、Fiddler简介 Fiddler是强大的抓包工具之一,它能记录所有客户端和服务器之间的HTTP和HTTPS请求,是web调试的利器。 Fiddler是位于客户端和服务端之间的HTTP代理,它的原理是以web代理服务器的形式进行工作的,使用的代理地址是:127.0.0.1,端口默认为8888,我们也可以通过设置进行修改。 Fiddler可以抓取支持HTTP代理的任意程序的数据包,如果要抓取https会

繁华似锦Fighting 1473

JavaSwing_4.2: JDialog、JOptionPane(对话框)

JDialog,对话框。使用 JDialog 类可以创建自定义有的对话框,或者调用 JOptionPane 中的多个静态方法快速创建各种标准的对话框。JOptionPane是 JavaSwing 内部已实现好的,以静态方法的形式提供调用,能够快速方便的弹出要求用户提供值或向其发出通知的标准对话框。

谢TS的博客 7万+

sleep期间读取所有_翻译 | JavaScript Everywhere第16章 创建,读取,更新和删除操作(^_^)...

点击上方蓝字关注我翻译 | 《JavaScript Everywhere》第16章 创建,读取,更新和删除操作(^_^)写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习...

weixin_39581739的博客 133

[cshell]个性化配置你的cshrc/tcshrc

本文介绍了csh/tcsh shell的配置优化方法,主要包括:1. 配置文件管理(全局和个人配置);2. 按键绑定设置(解决远程登录按键问题);3. 提示符个性化(包含颜色配置方案);4. 环境变量设置(如LSCOLORS、CLICOLOR等);5. 安全防护措施(防误删、防覆盖等);6. 实用alias命令集(简化操作、提高效率)。文章提供了详细的配置示例,并建议通过man tcsh获取更多帮助信息。这些配置能显著提升shell使用体验和工作效率。

元直的博客 6118

Java和Node.js的优点区别,Nodejs与Java你选哪一个?

网络上充斥着技术比较,但是为什么我们需要比较呢?我们试图找出编程语言、开发平台、框架、工具和API之间的差异,但原因是什么? 原因很简单——技术的最初选择会造成很大的不同。对于企业主来说,特定技术的使用决定了其产品的性能和增长可能性。对于开发团队,该技术定义了产品支持的易用性和最终迁移到其他平台的无缝性。对于开发人员来说,学习特定技术的决定可能是他们职业生涯中的关键点。 Java V.S. NodeJS 概述 乍一看,我们似乎在比较不能做比较的两样东西,一个是编程语言,另一个是运行环境,风牛马不相及

SUNXIOAJIE的博客 2823

用 SAML 2.0 Bearer Assertion 配置 ABAP OAuth 2.0 令牌交换

摘要: SAP系统集成中,身份跨系统传递是关键挑战。OAuth 2.0的SAML 2.0 Bearer Assertion grant机制通过SAML断言换取访问令牌,实现安全身份传递。配置核心在ABAP的SOAUTH2事务码,需绑定可信SAML身份提供商(IdP)并指定访问范围。实际应用中,需确保SSL加密传输,正确配置SAML IdP信任关系,并为OAuth客户端分配专用系统用户。常见问题包括证书不匹配、权限配置不当等,需分层控制权限边界以保障安全。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 838

10、利用智能合约实现公平的私有集合交集

本文探讨了利用智能合约实现公平的私有集合交集(PSI)的多种协议,重点分析了协议 Π 和 Π∗ 的气体成本与性能特点。同时对比了包括 Justitia 和 Anesidora 在内的现有方案,突出了仅使用智能合约实现硬币补偿公平性的优势。文中还介绍了相关密码学基础、安全模型及隐私保障机制,为在不同应用场景下选择高效、安全的 PSI 协议提供了理论支持和实践指导。

linux的博客 97

React 结合 Graphql 学习记录

1. Setup npm install @apollo/client graphql 2. Initialize ApolloClient import { ApolloClient, InMemoryCache, ApolloProvider, useQuery, gql } from "@apollo/client"; const client = new ApolloClient({ uri: 'https://48p1r2roz4.sse.codesandbo

weixin_42466309的博客 526

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Apollo useMutation 添加数据,改变数据

useMutation 修改后台数据,并且更新前端视图 修改了数据之后,Apollo 会根据ID自动更新视图,所以修改数据不需要手动改变本地缓存,删除,或者添加数据需要修改本地缓存或者改变了多个数据也需要修改本地缓存 import React from "react"; import { render } from "react-dom"; import { ApolloClient } fro...

weixin_43550927的博客 2752

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

翻译 | 《JavaScript Everywhere》第14章 使用Apollo Client

翻译 | 《JavaScript Everywhere》第14章 使用Apollo Client(_) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ…:*☆哎哟不错哦 第14章 使用Apollo Client 我清楚地记得我的第一个互联网连接。我用计算机的调制解调器

前端毛小悠的博客 636

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

翻译 | 《`JavaScript` `Everywhere`》第`7`章 用户帐户和身份验证(^`_`^)

翻译 | 《JavaScript Everywhere》第7章 用户帐户和身份验证(`_`) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code\_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ..:*☆哎哟不错哦 第7章 用户帐户和身份验证 想像一下自己走在黑暗的小巷里,你即将加入一个“超酷秘密俱乐部”(如果你正在阅

前端毛小悠的博客 537

翻译 | 《JavaScript Everywhere》第12章 使用React构建Web客户端(^_^)

翻译 | 《JavaScript Everywhere》第12章 使用React构建Web客户端(_) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ…:*☆哎哟不错哦 第12章 使用React构建Web客户端 超文本背后的原始想法是获取相关文档并将它们链接在一起:如

前端毛小悠的博客 377

翻译 | 《JavaScript Everywhere》第8章 用户操作(^_^)

翻译 | 《JavaScript Everywhere》第8章 用户操作(_) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ…:*☆哎哟不错哦 第8章 用户操作 想像你刚刚加入了一个俱乐部(还记得“超级酷人秘密俱乐部”吗?),当你第一次出现时,没有任何事可做。俱乐

前端毛小悠的博客 340

翻译 | 《JavaScript Everywhere》第23章 GraphQL和React Native

翻译 | 《JavaScript Everywhere》第23章 GraphQL和React Native(_) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ…:*☆哎哟不错哦 第23章 GraphQL和React Native 在宾夕法尼亚州匹兹堡的安迪·沃霍尔博

前端毛小悠的博客 327

翻译 | 《JavaScript Everywhere》第15章 Web身份验证和状态

翻译 | 《JavaScript Everywhere》第15章 Web身份验证和状态(_) 写在最前面 大家好呀,我是毛小悠,是一位前端开发工程师。正在翻译一本英文技术书籍。 为了提高大家的阅读体验,对语句的结构和内容略有调整。如果发现本文中有存在瑕疵的地方,或者你有任何意见或者建议,可以在评论区留言,或者加我的微信:code_maomao,欢迎相互沟通交流学习。 (σ゚∀゚)σ…:*☆哎哟不错哦 第15章 Web身份验证和状态 最近我和我的家人搬家了。填写并签署了几种表格(我的手仍然很累)后,我们就用钥

前端毛小悠的博客 319
上一篇: 绘图神器draw.io(写文必备)
下一篇: 翻译 | 《JavaScript Everywhere》第17章 部署Web应用程序
前端毛小悠
博客等级 码龄6年 33粉丝 45原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值