首页 > 解决方案 > Display Multi Dimensional Arrays/Matrix using react

问题描述

I started React recently and I am stuck on a matrix issue. Columns and Rows are taken as input from the user and should display a matrix as output. Here is my code:

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>
    );
  }
} 

I believe the fault is in my create array logic. On console.log it shows that my array is not storing anything. Any ideas on what I'm doing wrong? TIA

标签: javascriptreactjsmatrixmultidimensional-array

解决方案


您在 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));


推荐阅读