基本上在类组件中,我们使用如下所示的初始值在构造函数中预先初始化状态。
constructor(props){
super(props);
this.state = {
count: 0
}
}
但是在引入钩子之后,所有的类组件都变成了具有状态的功能组件。
但我的问题是如何使用 React v16.7.0 中的钩子将计数状态预初始化为 0
基本上在类组件中,我们使用如下所示的初始值在构造函数中预先初始化状态。
constructor(props){
super(props);
this.state = {
count: 0
}
}
但是在引入钩子之后,所有的类组件都变成了具有状态的功能组件。
但我的问题是如何使用 React v16.7.0 中的钩子将计数状态预初始化为 0
这是文档: https ://reactjs.org/docs/hooks-state.html
文档中的示例显示:
const [count, setCount] = useState(0);
传入 useState 的参数(例如本例中的“0”)是初始值。
如果你想在加载数据后设置初始状态(从 api 获取数据),你可以在 React 钩子中使用“useEffect”。它等于类组件中的“componentWillReceiveProps”。因此,当您在 useEffect 中设置状态值时,请确保避免无限循环,例如 ..
const [count,setcount] = useState(0)
useEffect(()=>{
setcount(api.data.count) // api.data.count from api after update store
},[])
这是一个如何在类中初始化状态的示例与带有钩子的函数:
基本上, 的第一个参数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>
<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>
<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>
根据 React 文档,您可以将初始值传递给 useState 挂钩。
const [state, setState] = useState(initialState);