绑定到数组的React组件不会重新呈现自身

时间:2018-03-13 08:38:33

标签: javascript reactjs

我创建了一个简单的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

1 个答案:

答案 0 :(得分:2)

请更改

this.state.items.map((data : any) => {
                <li>{data}</li>
              }) 

this.state.items.map((data : any) => <li>{data}</li>)