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

时间:2018-11-08 19:37:32

标签: javascript reactjs react-native react-hooks

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

     constructor(props){
          super(props);
          this.state = {
                 count: 0
          }
     }

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

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

4 个答案:

答案 0 :(得分:2)

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

文档中的示例显示:

const [count, setCount] = useState(0);

传递给useState的参数(例如,本例中为“ 0”)是初始值。

答案 1 :(得分:2)

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

const [count,setcount] = useState(0) 

 useEffect(()=>{
    setcount(api.data.count) // api.data.count from api after update store
  })

答案 2 :(得分:1)

根据React文档,您可以将初始值传递给useState挂钩。

const [state, setState] = useState(initialState);

https://reactjs.org/docs/hooks-reference.html#usestate

答案 3 :(得分:1)

这是一个如何在类与带钩子的函数中初始化状态的示例:

基本上,useState()的第一个参数是初始状态。

class CounterClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  
  render() {
    return <div>
      <strong>Class: </strong>
      <span>Count: {this.state.count}</span>&nbsp;
      <button onClick={() => this.setState({ 
        count: this.state.count + 1
      })}>Increase</button>
    </div>;
  }
}

function CounterFunction() {
  const [count, setCount] = React.useState(0); // Initial state here.
  return (
    <div>
      <strong>Function: </strong>
      <span>Count: {count}</span>&nbsp;
      <button onClick={() => 
        setCount(count + 1)}
      >Increase</button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <CounterClass />
    <hr/>
    <CounterFunction />
  </div>
, document.querySelector('#app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

相关问题