簡體   English   中英

reactjs中的狀態不會改變

[英]The state in reactjs doesn't change

盡管我使用了setState,返回了一個Object並在構造函數中綁定了函數,但是reactjs類中的狀態不會改變。這是我的代碼

export default class Vacations extends Component {
    constructor(props){
        super(props);
        this.state = {
            sat: false,
            sun: true,
            mon: false,
            tue: false,
            wed: false,
            thu: false,
            fri: false
        }
        this.handleEnabledChange = this.handleEnabledChange.bind(this);
    }

    handleEnabledChange(e){
        const targetName = e.target.name;
        const checkState = e.target.checked;
        console.log(targetName, checkState);
        this.setState((preState)=>{
            return Object.assign({},{
                ...preState,
                name: !checkState
            })
        }) 
    }

    render() {
    return (
      <div>        
        <Checkbox name="sat" checked={this.state.sat} label="Saturday" onChange={this.handleEnabledChange} disabled/>
        ...
      </div>
    )
  }
}

誰能幫我解決這個問題?

狀態已更改,但是您要向狀態添加新的屬性name

return Object.assign({},{
    ...preState,
    name: !checkState
})

您沒有更改sat的值,這就是為什么您的組件不顯示任何可見更新的原因。 注意如何永遠不要使用targetName

您應該這樣做:

this.setState({[targetName]: !checkState});

不需要使用回調,因為您不需要從先前的狀態讀取,也不必手動合並先前的狀態,React會為您完成。

簡單一點

handleEnabledChange(e){
    const targetName = e.target.name;
    const currentState = this.state[targetName]

    this.setState({
      [targetName]: !currentState
    })
}

我也注意到您在復選框上disabled道具。 復選框事件不會針對禁用的控件觸發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM