简体   繁体   English

React Hooks-我是否应该将“ useState”用于不变的状态?

[英]React Hooks - Should I use 'useState' for state that is unchanging?

When I initially learned React Component's I was always told to put everything in this.state . 当我最初学习React Component的时候,总是被告知将所有内容都放在this.state Whether it be some pieces of data that update frequently or some that never update at all. 是某些数据经常更新还是根本不更新。

However, with the implementation of React hooks, I'm not sure how frequently I should use useState even when the state will not update. 但是,通过React挂钩的实现,即使状态不会更新,我也不确定应该使用useState

Let me give you an example of some of my form logic: 让我给您举一些我的表单逻辑的例子:

const FormAuth = props => {
    //Frequently updates
    const [validInput, setValidInput] = useState({
        isCompletedForm: Boolean,
        firstName: Boolean,
        lastName: Boolean,
        email: Boolean,
        password: Boolean,
        confirmPassword: Boolean
    });

    // Never updates
    const [formSchema, setFormSchema] = useState({
        firstName: Joi.string().required(),
        lastName: Joi.string().required(),
        email: Joi.string().required().email().regex(emailRegex),
        password: Joi.string().required().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&?.]).{8,30}$/),
        confirmPassword: Joi.string().required()
    })

    // Never updates
    const [inputRef, setInputRef] = useState({
        firstNameRef: React.createRef(),
        lastNameRef: React.createRef(),
        emailRef: React.createRef(),
        passwordRef: React.createRef(),
        confirmPasswordRef: React.createRef()
    });

    // render some JSX
}

Here I have 3 states. 在这里,我有3个州。 The first state are Booleans that say if the inputs look good. 第一个状态是布尔值,表示输入是否看起来不错。 The second state is a formSchema which will never be updated. 第二种状态是formSchema,它将永远不会被更新。 Lastly, the third state is the Refs for each of the inputs which will also never be updated. 最后,第三个状态是每个输入的Ref,它们也将永远不会更新。

My question is: Would is make more sense to only have one state for validInputs since it updates frequently, and then for formSchema and inputRef create a const object with vanilla javascript? 我的问题是:validInputs 仅具有一种状态validInputs因为它经常更新,然后对于formSchemainputRef用香草javascript创建一个const对象? Or should everything go into state like before? 还是应该一切都像以前那样进入状态?

It seems to me that it would make more sense to only use useState if that state is going to update, but I'm trying to see what is the proper convention for hooks moving forward. 在我看来,仅当useState要更新时才使用useState更为有意义,但是我正在尝试查看对钩子前进的正确约定是什么。

You should only need to utilize state if: 仅在以下情况下才需要使用状态:

  • it controls some sort of element (like an input , select , textarea and so on). 它控制某种元素 (例如inputselecttextarea等)。
  • it's controlling some sort of data that needs to be manipulated (like a todo list that needs to have some items that are created, read, updated and deleted -- holds true for isomorphic apps as well, where some data needs to be manipulated on the front-end before being sent to a back-end for storage). 它控制着需要处理的某种数据(例如待办事项列表,需要创建,读取,更新和删除一些项目-对于同构应用程序也是如此,其中一些数据需要在前端,然后发送到后端进行存储)。
  • it's used for some sort of conditional rendering , where the DOM needs to be re-rendered with UI changes (like an isLoading boolean that shows a Spinner when true , but then displays some sort of layout when false ). 它用于某种条件渲染 ,其中DOM需要通过UI更改重新渲染(例如isLoading布尔值,当true时显示Spinner,但是当false时显示某种布局)。

There's no reason to clutter your state if it (whatever data type it is): Needs to be reusable across multiple components, is static, and doesn't update the DOM in any way (like a ref, or a field-level validation function or some sort static list of items). 如果状态(不管是哪种数据类型) ,则没有任何原因:需要在多个组件之间可重用,是静态的,并且不以任何方式(例如ref或字段级验证功能)更新DOM或某种静态项目列表)。

In simple terms, doesn't matter if it's a class component or a functional component with a hook, you'll only need to use state if it requires dynamically manipulating/controlling something within the DOM. 简而言之,无论是类组件还是带钩子的功能组件,只要它需要动态地操作/控制DOM中的某些内容,就只需要使用状态。

Here's a simple example of a form with some validation : 这是带有验证的表单的简单示例

编辑表单验证

i am scared that your frequently updated state are in object. 我担心您经常更新的状态不正确。 yeah you can do that but it not an good way to update your individual state by putting them in object. 是的,您可以这样做,但这不是通过将它们置于对象中来更新您的个人状态的好方法。

you don't need to keep data in state if it is not changing or updating. 如果数据没有更改或更新,则无需保持数据状态。 you can assign that type of data in some variables. 您可以在某些变量中分配该数据类型。

 //you can track your state value and state change by this function //you can use this same function in different component export function useFormInput(initialValue = "") { const [input, setInput] = useState(initialValue); function handleInputChange(e) { setInput(e.target.value); } return { value: input, onChange: handleInputChange, } } const FormAuth = props => { //Frequently updates //useFormInput function will return input value and unchange function const firstName = useFormInput(); const lastName = useFormInput(); // Never updates //here your not updating data is assigned in formSchema variable const formSchema = { firstName: Joi.string().required(), lastName: Joi.string().required(), email: Joi.string().required().email().regex(emailRegex), password: Joi.string().required().regex(/^(?=.*[az])(?=.*[AZ])(?=.*\\d)(?=.*[#$^+=!*()@%&?.]).{8,30}$/), confirmPassword: Joi.string().required() } // Never updates const inputRef = { firstNameRef: React.createRef(), lastNameRef: React.createRef(), emailRef: React.createRef(), passwordRef: React.createRef(), confirmPasswordRef: React.createRef() } return( <div> //firstname value and onchange function will be //assigned useing spread operator <input {...firstName} placeholder="first name"/> <input {...lastName} placeholder="last name"/> </div> ) } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM