在React中更新嵌套数组中的嵌套对象

时间:2019-06-19 09:31:44

标签: javascript arrays reactjs ecmascript-6 javascript-objects

预期效果:

  • 单击按钮->调用函数save->将对象p传递给函数update
  • 更新颜色数组(位于{a: 'purple', desc: 'grt', date: '12 -10-2019 '}数组中的第二个对象products

更新前:{a: 'purple', desc: 'grt', date: '12 -10-2019 '}

更新后:{a: 'violet', desc: 'gt', date: '12 -12-1980 '}

console.log中的错误:

Uncaught TypeError: this.props.product.colors.map is not a function

应用

class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      products: [  
            {
                colors: [{a:'orange', desc: 'grtrt',  date: '02-12-2019'}, {a:'purple', desc: 'grt',  date: '12-10-2019'}]
                desc: 'gfgfg',

            },
            {
                colors: [{a:'black', desc: 'g',  date: '12-12-2019'},  {a: 'white', {a:'black', desc: 'grtrt',  date: '12-12-2119'}, }, {a:'gray', desc:'', date: '01-01-2000'}],
                desc: 'gfgfgfg',

            }
        ],
        selectProductIndex: 0 //It is first object in products array
        index: 1  //It is second object in colors array
    }
  }

  update = (item) => {
    const {selectProductIndex} = this.state;

    this.setState(prevState => {
      return {
        products: [
          ...prevState.products.slice(0, selectProductIndex),
          Object.assign({}, prevState.products[selectProductIndex], {colors: item}),
          ...prevState.products.slice(selectProductIndex + 1)
        ]
      };
    });
  }

  render () {

    return (
        <div>
          <Items
            product={this.state.products[this.state.selectProductIndex]} 
            update = {this.update}
          /> 
        </div>

    )
  }

项目

class Items extends Component {


  render () {

    return (
      <ul>    
            {       
              this.props.product.colors
                .map((item, index) => 
                  <Item
                    key= {index}
                    index = {index}
                    time = {item}
                    update = {this.props.update}        
                  />
                )
            }
          </ul>   
      </div>      
    );
  }
}

项目

class Item extends Component {

  save = () => {
    const p = {
      a:'violet', desc: 'gt',  date: '12-12-1980'
    }

    this.props.update(p)
  }



  render() {

    return (
      <div>
        <button onClick={this.save}>Save</button>

      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:2)

您需要传递颜色项目的索引,然后进行相应的更新

class Item extends Component {

  save = () => {
    const p = {
      a:'violet', desc: 'gt',  date: '12-12-1980'
    }

    this.props.update(p, this.props.index)
  }



  render() {

    return (
      <div>
        <button onClick={this.save}>Save</button>

      </div>
    )
  }
}

,然后在最高的父级中

 update = (item, colorIndex) => {
    const {selectProductIndex} = this.state;

    this.setState(prevState => {
      return {
        products: [
          ...prevState.products.slice(0, selectProductIndex),
          Object.assign({}, prevState.products[selectProductIndex], {colors: prevState.products[selectProductIndex].colors.map((it,idx) => {
                if(idx === colorsIndex) { return item} 
                return it;
          })}),
          ...prevState.products.slice(selectProductIndex + 1)
        ]
      };
    });
  }

工作演示

const { Component } = React;
class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      products: [  
            {
                colors: [{a:'orange', desc: 'grtrt',  date: '02-12-2019'}, {a:'purple', desc: 'grt',  date: '12-10-2019'}],
                desc: 'gfgfg',

            },
            {
                colors: [{a:'black', desc: 'g',  date: '12-12-2019'}, {a:'black', desc: 'grtrt',  date: '12-12-2119'}, {a:'gray', desc:'', date: '01-01-2000'}],
                desc: 'gfgfgfg',

            }
        ],
        selectProductIndex: 0,
        index: 1
    }
  }

   update = (item, colorIndex) => {
      const {selectProductIndex} = this.state;

      this.setState(prevState => {
        return {
          products: [
            ...prevState.products.slice(0, selectProductIndex),
            Object.assign({}, prevState.products[selectProductIndex], {colors: prevState.products[selectProductIndex].colors.map((it,idx) => {
                  if(idx === colorIndex) { return item} 
                  return it;
            })}),
            ...prevState.products.slice(selectProductIndex + 1)
          ]
        };
      });
    }

  render () {

    return (
        <div>
          <Items
            product={this.state.products[this.state.selectProductIndex]} 
            update = {this.update}
          /> 
        </div>

    )
  }
}

class Items extends Component {
  render () {

    return (
      <ul>    
            {       
              this.props.product.colors
                .map((item, index) => 
                  <Item
                    key= {index}
                    index = {index}
                    time = {item}
                    update = {this.props.update}        
                  />
                )
            }
          </ul>     
    );
  }
}

class Item extends Component {

  save = () => {
    const p = {
      a:'violet', desc: 'gt',  date: '12-12-1980'
    }

    this.props.update(p, this.props.index)
  }



  render() {

    return (
      <div>
        <pre>{JSON.stringify(this.props.time)}</pre>
        <button onClick={this.save}>Save</button>

      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />