How does react control the checked property of the checkbox check box for loop output?

how do I control the checked property of the loop output checkbox in react? How should I define the state state?
I currently define an empty array checked, in state and then assign the array checked according to the number of loops in componentWillMount and componentWillReceiveProps. The checkbox, code for loop control dom is as follows:

 constructor(props) {
    super(props);
    this.state = {
      checked: []
    };
  }
componentWillReceiveProps(nextProps) {
    const { dispatch, organization, model } = nextProps;
    if (this.state.showCreateModal) {
      dispatch({ type: "createProjectModal/fetch", payload: organization })
    }
    
    // *** checkbox  checked 
    if (model.members.length > 0) {
      let arr = model.members.filter(item => item.user_id !== auth.getUser().user_id);
      let checked = [];
      arr.forEach(item => {
        let obj = {};
        obj[`${item.user_id}`] = false;
        checked.push(obj)
      });
      this.setState({ checked })
    }
  }

then in dom, direct one-to-one correspondence:

<ul>
        {members.length > 0 && members.map(item => {
          let index = null;
          for(let i = 0; i < checked.length; iPP) {
            if (checked[i] === item.user_id) {
              index = i;
              return index
            }
          }
          return (<li key={item.user_id}>
            <input
              type="checkbox"
              checked={checked[index]}        // ***state
              ref={(e) => {this.checkboxRef[item.user_id] = e}}
              value={item.user_id}
              onChange={(e) => {this.onSelectChange(item, e)}} 
            />
          </li>)
        })}
      </ul>

then in the onChange function of the check box, change the state of checked in state according to whether or not you check it:

if (e.target.checked){
  checked[index] = true;    //   true
} else {
  checked[index] = false;   //   false
}

but when I run it, I report the following error:

I know that this should be componentWillMount when checked is empty, so checkbox is an uncontrolled component (after the checked property does not work, checked is not empty, so the check box becomes a controlled component again, this should be the reason, but I don"t know how to solve it? Ask the great god to tell you a train of thought?

Mar.16,2021

try changing the checked attribute in input to

checked={checked[index] || false}

in addition, I think it is better to put this ckecked in the array members, otherwise it is easy to cause problems. Consider changing the data structure


didn't you solve it later? I have the same problem now, but I don't understand your solution

Menu