如何在 React 中使用钩子预初始化状态?

Hem*_*ari 10 javascript reactjs react-native react-hooks

基本上在类组件中,我们在构造函数中预先初始化状态,初始值如下所示。

     constructor(props){
          super(props);
          this.state = {
                 count: 0
          }
     }
Run Code Online (Sandbox Code Playgroud)

但是在引入钩子之后,所有的类组件都变成了带有状态的功能组件。

但我的问题是如何使用 React v16.7.0 中的钩子将计数状态预初始化为 0

Rya*_*ell 8

这是文档:https : //reactjs.org/docs/hooks-state.html

文档中的示例显示:

const [count, setCount] = useState(0);
Run Code Online (Sandbox Code Playgroud)

传入 useState 的参数(例如本例中的“0”)是初始值。


Dam*_*nka 5

如果你想在加载数据后设置初始状态(从 api 获取数据),你可以在 React 钩子中使用“useEffect”。它等于类组件中的“componentWillReceiveProps”。因此,当您在 useEffect 中设置状态值时,请确保避免无限循环,例如 ..

const [count,setcount] = useState(0) 

 useEffect(()=>{
    setcount(api.data.count) // api.data.count from api after update store
  },[])
Run Code Online (Sandbox Code Playgroud)