【发布时间】: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: [] }, () => console.log(this.state.qns, this.state.questions) );在控制台this.state.qns的值不为空? -
this.state.qns(点击提交时)的值变为空,但是当我在点击提交按钮后执行更改操作时,之前的数组值就到位了。就像,选定的值通过替换旧值插入到相对于索引的数组中。
-
可能是因为您使用的是全局可变数组
questions和qns。请仔细检查数据流,如果您仍然卡住,请与可重现的问题分享pen :)
标签: javascript arrays reactjs object filter