setState无法设置数组的值

时间:2019-03-01 06:24:03

标签: reactjs

在删除按钮被单击后,无法更改表。正确传递了值,但无法设置状态。状态在console.log中的第二个中已更改,但仍在显示所有数据。

class ShoppingList extends Component{
    state = {
        items: [
            {id: uuid(), name:'Eggs'},
            {id: uuid(), name:'Milk'},
            {id: uuid(), name:'Water'},
            {id: uuid(), name:'Tea'}
        ]

    }

// render方法从这里开始。

 render() {
        const {items} = this.state

        return(
            <div>
                <Container>
                <Button color="dark" style={{marginBottom:'2rem'}} onClick={() => {
                    const name = prompt('Enter Item');
                    if(name){
                        console.log('Entered')
                        this.setState(state =>({items:[...state.items, {id:uuid(), name}]}));

                    }
                }}>Add Item</Button>
                <ListGroup>
                    <TransitionGroup className="shopping-list">
                    {items.map(({id, name}) => (
                         <ListGroupItem>
                             <Button className="remove-button" color="danger" size="sm"
                             onClick={() => {const arrayCopy = this.state.items.filter((item) => item.id !== id);
                                 console.log(arrayCopy)
                                    this.setState({items: arrayCopy});
enter code here
                                 debugger;
                                 console.log('Check',items)
                                 console.log('Check',arrayCopy)
                             }}>&times;</Button>
                             {name}
                         </ListGroupItem>
                    ))}
                    </TransitionGroup>``
                </ListGroup>
                </Container>
            </div>

1 个答案:

答案 0 :(得分:0)

将这些console.log()放在回调函数中。因为this.setState()是一个异步函数。这样的控制台日志时,您将无法获得正确的值。

this.setState({items: arrayCopy}, () => {
  // Do what you need in this callback function
  console.log('Check',items)
  console.log('Check',arrayCopy)
});