首页 > 解决方案 > 如何提高我的编码标准以满足高级开发人员标准

问题描述

我最近刚刚完成了一家公司的技术测试,该公司申请了一名前端开发人员在 React 中工作,但我被拒绝了,没有任何反馈。所以我想知道下一次我可以做得更好和改进。我最近刚刚尝试申请前辈前端职位。这是他们给我的测试和我制作的东西。

这是他们测试的描述。

Create a component as a Form Control according to this design
The control should accept a label
The control should accept a validation function with configurable error message
The control can be incorporated inside a <form> and the selected option pushed up to the form.
The control should fire an event on change

Use the component you made in the previous step to create a form according to this design
Call this https://jsonplaceholder.typicode.com/users to populate list of the users. name should be displayed while id should be saved as the value in the form.
Add the required validation with the Please select a user error message.
Add 2 text fields, one for title and one for body both with required validation. (Don't worry about matching the design for the text fields.)
On submit of the form create a new post by sending the data to https://jsonplaceholder.typicode.com/posts. The request interface will look like
{
  "title": "foo",
  "body": "bar",
  "userId": 1
}

这是我制作的:

https://codesandbox.io/s/objective-thunder-322xi?file=/src/components/FormComponent.js

我知道它本来可以更好,但是有时间限制并且没有提供反馈,所以我不知道我哪里出错了。有人可以看看它,看看它是否符合他们的指示以及可以改进的地方。

标签: reactjs

解决方案


我浏览了您的代码,可能发现了一些我可能实现的代码略有不同。我不确定这是否是最好的编码标准,但可能是这样的。

  1. 我看到那里声明了很多 useStates(7 个声明)。我可能将一些相关的状态组合在一起。我在下面给出了一个示例供参考。在某些情况下,使用过多的声明可能不好。

  2. (const handleTitleChange = (ev) => setTitle(ev.target.value);)可以改进handleChange 函数 。这里处理的方式是对每个输入重复。所以,如果我有 10 个输入,handleChange 函数将有 10 行。在我的示例中,我给出了一种更好的处理变更的方法。请记住在输入字段和状态中放置相同的“名称”属性。此代码将为您在以后处理 onChange 和干净的代码时节省大量时间

  3. 我看到您使用 'id' 属性来引用表单中的 DOM 元素。这对 vanilla JS 来说很好,但在 React 中,最好不要使用。在 react 中有一个更好的方法叫做创建引用,即 React.createRef()。这提供了对 DOM 元素的简单引用。请参考我下面的例子。

  4. 验证处理方法可以改进。示例中的代码。

  5. 我看到填充内容后错误消息不会消失。所以,这需要改变。

我设法想出了另一种实现方式,它完全依赖于状态来进行表单验证处理。

带有 CREATE REF的代码不要介意 CSS 类,我使用引导程序

import React, { useState, useEffect } from 'react';

const TestComponent = () => {
  const [input, setInput] = useState({
    title: '',
    body: '',
  })

  const titleRef = React.createRef()
  const bodyRef = React.createRef()

  const handleChange = e => {
    setInput({ ...input, [e.target.name]: e.target.value })
  }

  const onHandleSubmit = e => {
    e.preventDefault();
    input.title ? titleRef.current.innerHTML = '' : titleRef.current.innerHTML = 'Please add a title';
    input.body ? bodyRef.current.innerHTML = '' : bodyRef.current.innerHTML = 'Please add a body';
    if (!input.title || !input.body) {
      return false;
    }
    console.log('Submit your form');
  }

  return (
    <div className="container py-5">
      <form onSubmit={onHandleSubmit}>
        <label>Title</label>
        <input type="text" name="title" value={input.title} onChange={handleChange} className="form-control" />
        <p ref={titleRef} style={{ color: 'red' }}></p>

        <label>Body</label>
        <input type="text" name="body" value={input.body} onChange={handleChange} className="form-control" />
        <p ref={bodyRef} style={{ color: 'red' }}></p>

        <button>Submit</button>
      </form>
    </div>
  );
}

export default TestComponent;

带有验证状态的代码

import React, { useState, useEffect } from 'react';

const TestComponent = () => {
  const [input, setInput] = useState({
    title: '',
    body: '',
    titleError: '',
    bodyError: '',
  })

  const handleChange = e => {
    setInput({ ...input, [e.target.name]: e.target.value })
  }

  const onHandleSubmit = e => {
    e.preventDefault();
    setInput({
      ...input,
      titleError: input.title ? '': 'Please add a title',
      bodyError: input.body ? '': 'Please add a body', 
    })
    console.log(input);
    if (!input.title || !input.body) {
      return false;
    }
    console.log('Submit your form');
  }

  return (
    <div className="container py-5">
      <form onSubmit={onHandleSubmit}>
        <label>Title</label>
        <input type="text" name="title" value={input.title} onChange={handleChange} className="form-control" />
        <p style={{ color: 'red' }}>{input.titleError}</p>

        <label>Body</label>
        <input type="text" name="body" value={input.body} onChange={handleChange} className="form-control" />
        <p style={{ color: 'red' }}>{input.bodyError}</p>

        <button>Submit</button>
      </form>
    </div>
  );
}

export default TestComponent;

PS根据场景会有更好的处理方法,但这可能会在某种程度上对您有所帮助。

编辑: 添加单选按钮来选择用户。userId 添加到状态

  const [input, setInput] = useState({
    title: '',
    body: '',
    titleError: '',
    bodyError: '',
    userId: '',
  })

为用户选择单选。

 <div>
      <input type="radio" name="userId" value="1" id="1"
        checked={input.userId === "1"} onChange={handleChange}
      />
      <label htmlFor="1">User 1</label>
    </div>
    <div>
      <input type="radio" name="userId" value="2" id="2"
        checked={input.userId === "2"} onChange={handleChange}
      />
      <label htmlFor="2">User 2</label>
    </div>

相同的 onChange 处理程序也适用于无线电选择。我看到您使用来自 useFetch 的响应来呈现用户。您可以使用相同的地图逻辑通过设置字段来呈现此收音机。将valueandid属性设置为来自响应等的用户 ID。


推荐阅读