【发布时间】:2020-04-04 22:57:21
【问题描述】:
我正在使用 React 钩子来处理应用程序状态,我想知道如何使用 props 初始化功能组件状态? useState 钩子文档说了一些明确的话,比如,
const [count, setCount] = useState(0);
我想通过传递给组件的 props 的值来初始化该 0 值。年长者,
import React from 'react';
export default class Sym extends React.Component{
constructor(props){
super(props);
this.state = {
sym : [0,3,2,8,5,4,1,6],
active: this.props.activeSym
}
this.setActive = this.setActive.bind(this);
}
setActive(itemIndex){
this.setState({
active: itemIndex
});
}
render(){
return (
<div><h1>{ this.state.sym[this.state.active]}</h1></div>
);
}
}
工作正常。父组件通过activeSym 属性和Sym 组件使用this.props.activeSym 在constructor 中初始化状态。是否有任何解决方法可以在功能组件中实现相同的功能?
【问题讨论】:
-
const [count, setCount] = useState(props.activeSym);? -
不需要调用超类构造函数?
-
它是一个功能组件,没有类或超类...
-
@jonrsharpe 您的解决方案运行良好。您可以发布描述性答案以供将来参考。我会接受的。谢谢
标签: reactjs initialization state react-hooks prop