首先没有切换复选框的代码
查询列表缺少第二个状态
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}
/>
工作演示
关于功能的进一步说明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
}