如何在 React 中正确使用 State() [英] How to useState() properly in React

查看:61
本文介绍了如何在 React 中正确使用 State()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的增量应用程序,你点击一个按钮,计数就会增加 1.

我的问题是:如何正确更新状态?

这是我想知道的两种方式,当然还有其他更好"的方式吗?选项请告诉我.

import React, {useState} from "react";const App = () =>{const [count, setCount] = useState(0)const 增量 = () =>{setCount(prevCount => prevCount + 1)}返回 (<div><h1>计数为{count}</h1><button onClick={increment}>加1</button>

)}导出默认应用

import React, {useState} from "react";const App = () =>{const [count, setCount] = useState(0)const 增量 = () =>{设置计数(计数 + 1)}返回 (<div><h1>计数为{count}</h1><button onClick={increment}>加1</button>

)}导出默认应用

您能告诉我哪一种是更新状态的最佳方式,为什么?谢谢!

解决方案

想象一个案例如下,你的意思是不同的:

const increment = () =>{setCount(prevCount => prevCount + 1)setCount(prevCount => prevCount + 1)}

或者:

const increment = () =>{设置计数(计数 + 1)设置计数(计数 + 1)}

不一样的行为.

I have a simple increment app where you hit a button and the count increments by 1.

My question is: how do I update the state properly?

Here are the two ways I am wondering between and of course if there is any other "better" option please do tell me.

import React, {useState} from "react"

const App = ()  => {   
    const [count, setCount] = useState(0)
    
    const increment = () => {
        setCount(prevCount => prevCount + 1)
    }
    
    return (
        <div>
            <h1>The count is {count}</h1>
            <button onClick={increment}>Add 1</button>
        </div>
    )
}

export default App

or

import React, {useState} from "react"

const App = ()  => {   
    const [count, setCount] = useState(0)
    
    const increment = () => {
        setCount(count + 1)
    }
    
    return (
        <div>
            <h1>The count is {count}</h1>
            <button onClick={increment}>Add 1</button>
        </div>
    )
}

export default App

Could you tell me which one is the best way of updating the state and why? Thank you!

解决方案

Imagine a case as follows, and you'll mean the difference:

const increment = () => {
    setCount(prevCount => prevCount + 1)
    setCount(prevCount => prevCount + 1)
}

Or:

const increment = () => {
    setCount(count + 1)
    setCount(count + 1)
}

Not the same behavior.

这篇关于如何在 React 中正确使用 State()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆