正如其他答案已经解释的那样,钩子 API 旨在为函数组件提供当前仅在类组件中可用的功能。钩子不应该用在类组件中。
可以编写类组件以更轻松地迁移到功能组件。
使用单一状态:
class MyDiv extends Component {
state = {sampleState: 'hello world'};
render(){
const { state } = this;
const setState = state => this.setState(state);
return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
}
}
转换为
const MyDiv = () => {
const [state, setState] = useState({sampleState: 'hello world'});
return <div onClick={() => setState({sampleState: 1})}>{state.sampleState}</div>;
}
请注意,useState
状态设置器不会自动合并状态属性,这应该用setState(prevState => ({ ...prevState, foo: 1 }))
;覆盖。
具有多个状态:
class MyDiv extends Component {
state = {sampleState: 'hello world'};
render(){
const { sampleState } = this.state;
const setSampleState = sampleState => this.setState({ sampleState });
return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
}
}
转换为
const MyDiv = () => {
const [sampleState, setSampleState] = useState('hello world');
return <div onClick={() => setSampleState(1)}>{sampleState}</div>;
}