【问题标题】:Array not getting cleared to null or empty in setState on click in react在单击反应时,数组未在 setState 中清除为 null 或为空
【发布时间】:2020-08-28 06:59:08
【问题描述】:

点击反应时,setState 中的数组未清除为 null 或为空。

当我点击提交按钮时,数组必须设置为[]。它设置为 [],但是在更改之前的项目数组时会进入数组。

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;

在按钮点击提交时,数组必须设置为 [] 并且在更改时,值必须设置为相对于其索引的空数组。

【问题讨论】:

  • 你的意思是this.setState({ qns: [] }, () =&gt; console.log(this.state.qns, this.state.questions) );在控制台this.state.qns的值不为空?
  • this.state.qns(点击提交时)的值变为空,但是当我在点击提交按钮后执行更改操作时,之前的数组值就到位了。就像,选定的值通过替换旧值插入到相对于索引的数组中。
  • 可能是因为您使用的是全局可变数组questionsqns。请仔细检查数据流,如果您仍然卡住,请与可重现的问题分享pen :)

标签: javascript arrays reactjs object filter


【解决方案1】:
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 = []
}

【讨论】:

  • 将最后一行添加到提交功能后,问题仍然存在。
  • @skp 我更新了我的答案。如果它不起作用。与可重现的问题共用一支笔
【解决方案2】:

终于找到了解决办法。

添加 componentDidMount 并将问题变量设置为 null 后解决了我的问题。

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

感谢大家的努力和回复!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 2020-09-25
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 2018-07-27
    相关资源
    最近更新 更多