我有以下问题。 我想初始化我的主要组件App的状态,其中一个状态属性必须访问另一个。
执行以下操作会收到此错误-TypeError:无法读取未定义的属性“ items”。
class App extends Component {
state = {
items: [
'itemOne',
'itemTwo',
],
currentItem: this.state.items[0]
}
我认为状态尚未设置,因此items数组不存在。 使用componentDidMount()设置currentItem的状态可能会解决此问题,但是由于currenItem作为prop传递给其他组件,因此可能会发生其他错误。
管理此问题的最优雅,最标准的方法是什么?
答案 0 :(得分:1)
您可以在构造函数中做到这一点:
class App extends Component {
constructor(props) {
super(props);
const items = [
'itemOne',
'itemTwo',
]
this.state = {
items: items,
currentItem: items[0];
}
}
答案 1 :(得分:0)
在渲染之前,不能将状态的值设置为其他状态。
在这种情况下,您可以使用生命周期componentDidMount()
。
class App extends Component {
state = {
items: ['itemOne', 'itemTwo'],
currentItem: 'itemOne' || null //You can define the initial value or null
}
componentDidMount(){
setState({...this.state, currentItem: this.state.items[0]});
}