简体   繁体   中英

Array not getting cleared to null or empty in setState on click in react

Array not getting cleared to null or empty in setState on click in react.

When I click on the submit button, the array must be set to []. It is setting to [], but on change the previous array of items comes into the array.

let questions = [];
let qns = [];

class App extends Component {
  constructor(props) {
    super(props);    
    this.state = {
      btnDisabled: true,
      //questions: [],
    };    
  }

  changeRadioHandler = (event, j) => {
    this.setState({ checked: true });
    const qn = event.target.name;
    const id = event.target.value;
    let idVal = this.props.dat.mat.opts;
    let text = this.props.dat.mat.opt;
    let userAnswer = [];
    for (let j = 0; j < text.length; j++) {
      userAnswer.push(false);
    }
    const option = text.map((t, index) => ({
      text: t.text,
      userAnswer: userAnswer[index],
    }));
    const elIndex = option.findIndex((element) => element.text === id);
    const options = { ...option };
    options[elIndex] = {
      ...options[elIndex],
      userAnswer: true,
    };
    const question = {
      options,
      id: event.target.value,
      qn,
    };   
    questions[j] = options;
    qns = questions.filter((e) => {
      return e != null;
    });    
    console.log(qns, qns.length);
    this.setState({ qns });
    if (qns.length === idVal.length) {
      this.setState({
        btnDisabled: false,
      });
    }
  };

  submitHandler = () => {    
    console.log(this.state.qns, this.state.questions);    
    this.setState({ qns: [] }, () =>
      console.log(this.state.qns, this.state.questions)
    );
  };

  render() {
    return (
      <div class="matrix-bd">        
        {this.props.dat.mat && (
          <div class="grid">
            {this.props.dat.mat.opts.map((questions, j) => {
              return (
                <div class="rows" key={j}>
                  <div class="cell main">{questions.text}</div>
                  {this.props.dat.mat.opt.map((element, i) => {
                    return (
                      <div class="cell" key={i}>
                        <input
                          type="radio"
                          id={j + i}
                          name={questions.text}
                          value={element.text}
                          onChange={(event) =>
                            this.changeRadioHandler(event, j)
                          }
                        ></input>
                        <label htmlFor={j + i}>{element.text}</label>
                      </div>
                    );
                  })}
                </div>
              );
            })}
          </div>
        )}
        <div>
          <button
            type="button"           
            class="btn btn-primary"
            disabled={this.state.btnDisabled}
            onClick={this.submitHandler}
          >
            SUBMIT
          </button>
        </div>
      </div>
    );
  }
}

export default App;

On button click submit, the array must be set to [] and when on change, the value must be set to the emptied array with respect to its index.

changeRadioHandler = (event, j) => {
 // the better way is use local variable
 let questions = [];
 let qns = [];
 ...

}


submitHandler = () => {    
 console.log(this.state.qns, this.state.questions);  
 this.setState({ qns: [] }, () =>
  console.log(this.state.qns, this.state.questions)
  )}
 // clear the previous `qns`
 // if u use local variable. you don't need those lines
 // this.qns = []
 // this.questions = []
}

Finally, found out the solution.

After adding componentDidMount and setting questions variable to null solved my issue.

componentDidMount = () => {
    questions = [];
  };

Thanks all for your efforts and responses!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM