Unicorns VO 面试真题解析:React 接口搜索帖子与实时过滤

30次阅读
没有评论

Create a React app that allows a user to search entries received from the following “posts” API:

https://jsonplaceholder.typicode.com/posts

A post will have the following structure:

  • userId (integer)
  • id (integer)
  • title (string)
  • body (string)

Requirements:

  • Fetch the data just once, at initialization (this will be an in-memory search)
  • Display an input field where the user will type their search term
  • Searching should occur with each keystroke in the search field
  • Searching should begin once the user has typed 2+ characters
  • Display a list of matching posts
  • A post is a “match” if the current search term is anywhere in the post’s title or body (case insensitive)

Display format:

  • Display the full title of the post
  • Display a 25 character excerpt of the body of the post
  • If the search term is found in the body of the post, display it in the middle of the excerpt
  • Otherwise, display the first 25 characters of the body

这道题考察的是 React 中的接口拉取、受控输入框和前端内存搜索。页面初始化时只请求一次 JSONPlaceholder 的 posts 数据,随后把结果保存在本地状态中;用户在输入框中每输入一个字符就触发过滤,但只有当搜索词长度达到 2 个字符后才开始展示结果。匹配规则需要同时检查 title 和 body,且不区分大小写。渲染时要显示完整标题,以及 body 的 25 字符摘要;如果命中的是 body 中的内容,摘要应尽量让命中的搜索词出现在中间位置,否则直接展示 body 的前 25 个字符即可。

正文完
 0