【问题标题】:How to useState() properly in React如何在 React 中正确使用 State()
【发布时间】:2021-10-15 10:31:36
【问题描述】:

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

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

这是我想知道的两种方式,当然,如果还有其他“更好”的选择,请告诉我。

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

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

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

【问题讨论】:

    标签: reactjs react-hooks use-state


    【解决方案1】:

    想象一个案例如下,你就会明白其中的不同:

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

    或者:

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

    不一样的行为。

    【讨论】:

    • 很有趣,那么我猜使用第一个选项会更明智?
    • 这取决于:您的应用程序的预期行为应该是什么?如果它是一个购物车,作为用户,我不希望意外点击更多会导致购物车中的额外物品。因此,我会更好地看到第二种方法(作为原则)。相反,对于缩放图片的组件(每次单击增加/减少缩放),第一种方法似乎更合适。
    【解决方案2】:

    通常在使用useCallback时,最好使用setCount(x=> x + 1);

    const onIncr = React.useCallback(()=> {
      setCount(x=> x + 1)
    }, [])
    

    const onIncr = React.useCallback(()=> {
       setCount(count + 1)
    }, [count]) 
    

    tips,这个例子可以转化成

    const [count, increment] = React.useReducer((x)=> x + 1, 0);
    return <button onClick={increment}>{count}</button>
    

    此技术通常用于切换值

    const [isOpen, toggle] = React.useReducer(x=> !x, false);
    return (
    <>
      <button onClick={toggle}>open dialog</button>
      <Dialog open={isOpen} onClose={toggle}></Dialog>
    <>
     )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 2018-07-19
      • 2017-09-30
      • 2016-09-28
      • 2018-03-25
      • 1970-01-01
      相关资源
      最近更新 更多