无法呈现状态,但可以console.log



我有一个定义如下的状态:

state = {
items: [
{id: 0, value: 0},
{id: 1, value: 0},
],
};

当我在构造函数中控制台.log(this.state.items[0].id(时,我得到了正确的值。

但当我试图把它渲染成这样时:

render() {
return (
<div>
<table>
<tr>
<th id="d0" onClick={(e)=>this.onClick(e)}>{this.state.items[0].id}</th>
....

上面写着";无法读取未定义的"的属性"0";

渲染是否发生在状态初始化之前,因此在尝试渲染时未定义?

class App extends React.Component {
/**
* @param {object} props
*/
state = {
items: [
{ id: 0, value: 0 },
{ id: 1, value: 0 },
],
};
constructor(props) {
super(props);
console.log(this.state.items[0].id);
}
render() {
return (
<div>
<table>
<tbody>
<tr>
<th id="d0" onClick={(e) => this.onClick(e)}>th</th>
<th id="d1">h</th>
</tr>
</tbody>
</table>
</div>
);
}
onClick(e) {
this.setState({ day0: 6 });
}
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

您的状态应该在构造函数中设置

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{ id: 0, value: 0 },
{ id: 1, value: 0 },
]
}
}
render() {
return (
<div>
<table>
<tr>
<th id="d0" onClick={(e)=>this.onClick(e)}>{this.state.items[0].id}</th>
</tr>
</table>
</div>
);
}
}

您对状态的初始化不正确。状态应该在基于类的组件的构造函数内部初始化。请将状态初始化更新为:

class App extends React.Component {
/**
* @param {object} props
*/
constructor(props) {
super(props);
this.state = {
items: [
{ id: 0, value: 0 },
{ id: 1, value: 0 },
],
};
}
render() {
return (
<div>
<table>
<tbody>
<tr>
<th id="d0" onClick={(e) => this.onClick(e)}>{this.state.items[0].id}</th>
<th id="d1">h</th>
</tr>
</tbody>
</table>
</div>
);
}
onClick(e) {
this.setState({ day0: 6 });
}
}
ReactDOM.render(<App />, document.querySelector('.react'));

相关内容

最新更新