如何解决状态变更问题,该问题落后于OnClick事件



我想通过单击来更改状态,但它落后了一步。我没有 t understand what错误。

class Products extends Component {        
    state = {
            product: null
        }
    render() {       
        const handalebar = (event) => {
            event.preventDefault();
            const product_code = event.target.closest('.card').getAttribute('id');
            this.setState({
                product: product_code
            })                
            console.log(this.state.product);
        }

setState是异步的,使用回调来记录更新的状态:

setState(
  { product: product_code },
  () => console.log(this.state.product)
);

我认为您应该在渲染函数之外写下把手函数,并将状态对象放入构造函数,不要忘记绑定函数。

class Products extends Component{
                constructor(props){
                      super(props)
                      this.state = {
                               product: null
                              }
                      this.handlebar = this.handlebar.bind(this);
                 }

     handlebar = (event) => {
            event.preventDefault();
            const product_code = event.target.value;
            this.setState({
                product: product_code
            })                
           render(){
               console.log(this.state.product);
           return (
                    <div>
                    </div>
           )
}
}

最新更新