首页 > 解决方案 > Checkbox didn't get unchecked once set it to checked in React

问题描述

I am made a dynamic data table in React that gets all its data from a JSON file. One of the table column fields is a 'answered-status' which used to give answer status of the inquiry whether it is answered or not.

I have an 'answered' key with value either answered or unanswered in JSON. When I used that value with my checkbox. I wasn't able to switch back to the original value. Please check below sandbox link for more detail. I use the Bootstrap 4 custom checkbox.

https://p7h9x.csb.app/

标签: reactjstypescriptreact-forms

解决方案


首先没有切换复选框的代码

查询列表缺少第二个状态

constructor(props) {
    super(props);
    this.state = {
        searchInquiries: null,
        answerStatus: "all",
        inquiresList : InquiresList //<--- settting into state for maintaining change
    };
}

toggleCheck = (event,inquiry_id) => {
    const inquiresList = this.state.inquiresList.map(inquiry => {
        return inquiry.id === inquiry_id ? { ...inquiry , "answered" : event.target.checked ? "answered" : "unanswered" } : inquiry
    })
    this.setState({inquiresList}); //<---- Updating state 
};

// There is no need of turnery operator for checked unchecked whole input
<input
    type="checkbox"
    ref="answerStatus"
    checked={inquiry.answered === "answered"} // <---- HERE
    onChange={(e) => this.toggleCheck(e,inquiry.id)} // <---- HERE
    className="custom-control-input"
    id={"answer-status-" + inquiry.id}
    name={"answer-status-" + inquiry.id}
/>

工作演示

编辑so-checkbox-toggle

关于功能的进一步说明inquiresList

const inquiresList = this.state.inquiresList.map(inquiry => {
    return inquiry.id === inquiry_id ? // checking if inquiry id match
            // if matched we need to update that object
            { ...inquiry , "answered" : event.target.checked ? "answered" : "unanswered" } :  
            // else pass the same object as it is
            inquiry // else pass the same object as it is
})


// Why this way?
// because, we don't want to mutate state directly
{ 
    ...inquiry , // <-- extract all elements inside inquiry
    "answered" : event.target.checked ? "answered" : "unanswered" // <--- We are override the value with it
}


推荐阅读