Reactjs React-初始化状态并在第一次渲染之前访问状态
我有以下问题。 我想初始化我的主组件应用程序的状态,其中一个状态属性必须访问另一个 执行以下操作后,我得到了this错误-TypeError:无法读取未定义的属性'items'Reactjs React-初始化状态并在第一次渲染之前访问状态,reactjs,Reactjs,我有以下问题。 我想初始化我的主组件应用程序的状态,其中一个状态属性必须访问另一个 执行以下操作后,我得到了this错误-TypeError:无法读取未定义的属性'items' class App extends Component { state = { items: [ 'itemOne', 'itemTwo', ], currentItem: this.state.items[0] } 我假设状态尚未设置,因此items数组不
class App extends Component {
state = {
items: [
'itemOne',
'itemTwo',
],
currentItem: this.state.items[0]
}
我假设状态尚未设置,因此items数组不存在。
使用componentDidMount()设置currentItem的状态可以解决此问题,但由于currenItem作为道具传递给其他组件,因此可能会发生其他错误
最优雅、最标准的管理方式是什么?您可以在构造函数中完成:
class App extends Component {
constructor(props) {
super(props);
const items = [
'itemOne',
'itemTwo',
]
this.state = {
items: items,
currentItem: items[0];
}
}
在渲染之前,不能将状态的值设置为其他状态。 在这种情况下,您可以使用lifecycle
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]});
}