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

标签 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>
    )
  }
}

最佳答案

你需要传递颜色项的索引,然后相应地更新它

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" />

关于javascript - 在 React 中更新嵌套数组中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56664469/

相关文章:

javascript - 如何在循环中生成react html

javascript - Provider 中的无效 Prop child

javascript - `setState` 未与UI同步

javascript - 由于添加 Logo ,单选按钮变得错位

javascript - 配置模拟客户端

javascript - Extjs4 树面板的文件夹对齐问题

javascript - 如果 polyfill 脚本下载失败会发生什么?

php - 将数组中的多行插入具有唯一 ID 的表中

c++ - 链表数组大小不同

python - 如何将一串字节转换为int?