Javascript 绑定到数组的React组件不';重新呈现自己
我创建了一个简单的React组件,它绑定到数组“items”。现在,通过单击“添加项”按钮来更新基础状态。状态正在更新,但React不会自行重新呈现。有人能帮忙吗Javascript 绑定到数组的React组件不';重新呈现自己,javascript,reactjs,Javascript,Reactjs,我创建了一个简单的React组件,它绑定到数组“items”。现在,通过单击“添加项”按钮来更新基础状态。状态正在更新,但React不会自行重新呈现。有人能帮忙吗 interface IComponentState { items: any[]; } class UpdateArrayDemo extends React.Component<{}, IComponentState> { constructor(props) { super(props); t
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
接口IComponentState{
项目:任何[];
}
类UpdateArrayDemo扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
项目:新数组()
};
this.onAddItem=this.onAddItem.bind(this);
}
在这里添加一些状态
onAddItem(){
const items=this.state.items;
//添加一项
让项目=日期();
项目。推送(项目)
这是我的国家({
项目:项目
}, () => {
console.log(this.state.items);
});
}
render():JSX.Element{
返回(
添加项目
{
(this.state!=null&&this.state.items!=null)?
this.state.items.map((数据:any)=>{
- {data}
})
: ''
}
)
}
}
ReactDOM.render(
,
document.getElementById('root'))
);
//参考代码笔上的链接
//https://codepen.io/yoghcl/pen/BroGYO?editors=0010
请更改
this.state.items.map((data : any) => {
<li>{data}</li>
})
this.state.items.map((数据:any)=>{
{data}
})
到
this.state.items.map((数据:any)=>{data} )
映射函数没有返回任何内容。请移除
周围的大括号,或添加return
。谢谢,它正在工作。我很想知道问题出在哪里。
this.state.items.map((data : any) => <li>{data}</li>)