有可能在React中使用React.useState(()=> {})吗? [英] is it possible to React.useState(() => {}) in React?

查看:79
本文介绍了有可能在React中使用React.useState(()=> {})吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用函数作为我的React Component的状态?

is it possible to use a function as my React Component's state ?

示例代码在这里:

// typescript 
type OoopsFunction = () => void;

export function App() {
    const [ooops, setOoops] = React.useState<OoopsFunction>(
        () => console.log('default ooops')
    );

    return (
        <div>
            <div onClick={ ooops }>
                Show Ooops
            </div>

            <div onClick={() => {
                setOoops(() => console.log('other ooops'))
            }}>
                change oops
            </div>
        </div>
    )
}

但它不起作用... defaultOoops 将在开始时以及单击 change时调用哎呀,点击 Show Ooops 后,其他哎呀将立即记录到控制台而不进行日志记录再次。

but it doesn't works ... the defaultOoops will be invoked at very beginning, and when clicking change oops, the otrher ooops will be logged to console immediately not logging after clicking Show Ooops again.

为什么?

我是否可以将函数用作组件的状态?

is it possible for me to use a function as my component's state ?

还是React有其特殊的方式来处理函数状态

or else React has its special ways to process such the function state ?

推荐答案

可以使用挂钩将函数设置为状态,但是因为状态可以使用返回的函数进行初始化和更新初始状态或更新状态,您需要提供一个函数,该函数又返回要置于状态的函数。

It is possible to set a function in state using hooks, but because state can be initialized and updated with a function that returns the initial state or the updated state, you need to supply a function that in turn returns the function you want to put in state.

const { useState } = React;

function App() {
  const [ooops, setOoops] = useState(() => () => console.log("default ooops"));

  return (
    <div>
      <button onClick={ooops}>Show Ooops</button>

      <button
        onClick={() => {
          setOoops(() => () => console.log("other ooops"));
        }}
      >
        change oops
      </button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

这篇关于有可能在React中使用React.useState(()=&gt; {})吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆