我创建了一个简单的React组件,它绑定到数组" items"。现在通过点击" Add Item"更新基础状态。按钮。状态正在更新,但React不会以某种方式重新呈现它。任何人都可以帮忙吗?
interface IComponentState {
items: any[];
}
class UpdateArrayDemo extends React.Component<{}, IComponentState> {
constructor(props) {
super(props);
this.state = {
items: new Array()
};
this.onAddItem = this.onAddItem.bind(this);
}
adding some state here
onAddItem() {
const items = this.state.items;
//add one item
let item = Date();
items.push(item)
this.setState({
items : items
}, () => {
console.log(this.state.items);
});
}
render() : JSX.Element {
return(
<div>
<button onClick={this.onAddItem}>Add Items</button>
<ul>
{
(this.state != null && this.state.items != null) ?
this.state.items.map((data : any) => {
<li>{data}</li>
})
: ''
}
</ul>
</div>
)
}
}
ReactDOM.render(
<UpdateArrayDemo />,
document.getElementById('root')
);
//refer link on code pen
//https://codepen.io/yoghcl/pen/BroGYO?editors=0010
答案 0 :(得分:2)
请更改
this.state.items.map((data : any) => {
<li>{data}</li>
})
到
this.state.items.map((data : any) => <li>{data}</li>)