我最近开始使用React,而且我遇到了矩阵问题。列和行作为用户的输入,应显示矩阵作为输出。这是我的代码:
class App extends Component {
constructor(props){
super(props);
this.state = {
array1 : [],
array2 : [],
col1: null,
row1 : null,
}
this.handleCol1Change = this.handleCol1Change.bind(this);
this.handleRow1Change = this.handleRow1Change.bind(this);
}
handleCol1Change(e){
this.setState({
col1 : e.target.value
})
}
handleRow1Change(e){
this.setState({
row1 : e.target.value
})
}
createarray1(){
for(let i=0; i < this.state.row1; i++){
let row = []
this.state.array1.push(row);
for(let j=0; j < this.state.col1; j++){
let col = "1"
this.state.array1.push(col);
}
return this.state.array1
}
}
handleSubmit(){
this.createarray1()
}
render() {
return (
<div>
<h3>Enter Dimensions</h3>
<form>
<h1>Matrix 1</h1>
<input placeholder="Columns" onChange={this.handleCol1Change}/>
<input placeholder="Rows" onChange={this.handleRow1Change}/>
<button type="submit" onSubmit={this.handleSubmit.bind(this)}>Enter Dimensions</button>
</form>
{console.log("array",this.state.array1,"array2",this.state.array2)}
</div>
);
}
}
我相信错误在于我的创建数组逻辑。在console.log
上,它表明我的数组没有存储任何内容。关于我做错了什么的任何想法? TIA
您在createArray()方法中遇到了一些问题,您需要构建该行,然后将其添加到数组中。另外,正如@ageoff所说,你需要调用setState
而不是直接使用this.state
。这是您的代码更改,以保持它与您目前的相似 - 但它应该工作。
createarray1
现在只返回数组,handleSubmit
函数设置状态。
编辑:我现在改变了createarray1
,这是一个纯函数,你传入rowCount和colCount。现在你可以检查createarray1
是否独立工作:
createarray1(rowCount, colCount){
let myarr = [];
for(let i=0; i < rowCount; i++){
let row = []
for(let j=0; j < colCount; j++){
let col = "1"
row.push(col);
}
myarr.push(row);
}
return myarr;
}
handleSubmit(){
this.setState({
array1: this.createarray1(this.state.row1, this.state.col1)
});
}
这是它自己的功能,以显示它正在创建正确的数组:
let createarray1 = function(rowCount, colCount){
let myarr = [];
for(let i=0; i < rowCount; i++){
let row = []
for(let j=0; j < colCount; j++){
let col = "1"
row.push(col);
}
myarr.push(row);
}
return myarr;
}
console.log(createarray1(2,3));
当你调用this.state.array1.push
时,你正在直接修改状态。你应该使用setState()
。如果你只是推动状态值,那么你可以使用setState({array1: [...this.state.array1, row]})