在React.js中循环遍历状态对象

时间:2018-07-09 07:03:48

标签: reactjs loops state

我有9个键的状态。我希望每次应用运行时,键的每个值都是1-9之间的随机数,并且每个键的所有值必须唯一。我该如何查看对象中的每个键,并每次给它们一个不同的数字?

import React, { Component } from 'react'


class Grid extends Component {

constructor(props) {
    super(props)
    this.state = {
        input1: '',
        input2: '',
        input3: '',
        input4: '',
        input5: '',
        input6: '',
        input7: '',
        input8: '',
        input9: '',
    };

    this.handleChange = this.handleChange.bind(this);
}

componentWillMount() {
    var numArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

    Object.keys(this.state).map((n)=> console.log(n));

}



handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    this.setState({
        [name]: value
    });
}


render() {
    return (
        <div className="content">
            <form className="grid">
                <label className="grid__container">
                    <input  name="input1" value={this.state.input1} onChange={this.handleChange} className="grid__container--item" />
                    <input  name="input2" value={this.state.input2} onChange={this.handleChange} className="grid__container--item" />
                    <input  name="input3" value={this.state.input3} onChange={this.handleChange} className="grid__container--item" />
                    <input  name="input4" value={this.state.input4} onChange={this.handleChange} className="grid__container--item" />
                    <input  name="input5" value={this.state.input5} onChange={this.handleChange} className="grid__container--item" />
                    <input  name="input6" value={this.state.input6} onChange={this.handleChange} className="grid__container--item" />
                    <input  name="input7" value={this.state.input7} onChange={this.handleChange} className="grid__container--item" />
                    <input  name="input8" value={this.state.input8} onChange={this.handleChange} className="grid__container--item" />
                    <input  name="input9" value={this.state.input9} onChange={this.handleChange} className="grid__container--item" />
                </label>
            </form>
        </div>
    );
}
}

 export default Grid;

您可以在componentWillMount生命周期方法中看到,我试图遍历该对象,但它只是将键返回到数组中。

1 个答案:

答案 0 :(得分:0)

您可以使用Math.floor(Math.random() * numArr.length)随机选择索引,然后将该值添加到state,然后从数组中删除该索引处的值。

const state = {
  input1: '', input2: '', input3: '',
  input4: '', input5: '', input6: '',
  input7: '', input8: '', input9: '',
};

const numArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

const newState = Object.keys(state).reduce((acc, key) => {
  const index = Math.floor(Math.random() * numArr.length);
  const number = numArr.splice(index, 1)[0];

  return Object.assign({}, acc, {
    [key]: number
  });
}, {});

console.log(newState);