如何在 React 中使用钩子预初始化状态? [英] How can I pre initialise state with hooks in React?
本文介绍了如何在 React 中使用钩子预初始化状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上在类组件中,我们在构造函数中预先初始化状态,初始值如下所示.
Basically in class components we pre initialise state in constructor with initial values like below.
constructor(props){
super(props);
this.state = {
count: 0
}
}
但是在引入钩子之后,所有的类组件都变成了带有状态的功能组件.
But after hooks are introduced all the class components became functional components with state.
但我的查询是如何在 React v16.7.0 中使用钩子将计数状态预初始化为 0
But my query is how can I pre initialise count state to 0 with hooks in React v16.7.0
推荐答案
文档如下:https://reactjs.org/docs/hooks-state.html
文档中的示例显示:
const [count, setCount] = useState(0);
传入 useState 的参数(例如本例中的0")是初始值.
The parameter passed in to useState (e.g. "0" in this case) is the initial value.
这篇关于如何在 React 中使用钩子预初始化状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文