繁体   English   中英

Append 项目从一个数组到另一个数组,然后如果单击按钮,则将最后一项移回

[英]Append items from one array to another, then if button is clicked on, move the last item back

我正在构建一个 function 来帮助我从 arrays 移动项目。 组件呈现各个部分:

  1. 填充数组 - 一个空数组,根据单词的长度生成动态数量的按钮。
  2. bottomLetters - 一个字母数组,其中单词已被拆分为每个单独的字母。 单击该字母后,append 将成为填充数组中的一个新项目。
  3. 删除按钮 - 单击后,删除 topLetter 数组中的最后一项并将其添加到 bottomLetters 数组中。

现在我的代码有两个问题:

  1. 它不会自动更新渲染。 我必须保存代码沙箱才能生成结果。
  2. 单击删除按钮时,它会破坏 bottomLetters 数组中项目的值。 (例如,尝试单击 bottomLetters 数组中的三个项目,点击保存,然后点击删除按钮,它不会将项目移回数组)。

这是我的代码示例: https://codesandbox.io/s/show-and-hide-in-react-forked-nh9l2?file=/src/MyApp.js

您需要state object 来存储需要由 React 自动更新的局部变量。 为了能够使用state object,您必须将功能组件代码转换为class 组件

以下是我为解决问题所做的一些更改。

import React, { Component } from 'react';

export class myApp extends Component {
  state = {
    word: ['1234'],
    topLetters: [],
    bottomLetters: [],
    filledArray: [],
  };

  componentDidMount() {
    this.setState({
      bottomLetters: [...this.state.word[0]],
      filledArray: new Array(this.state.word[0].length).fill(null),
    });
  }

  handleLetters2Click = (letter, id) => {
    this.setState({ topLetters: [...this.state.topLetters, { letter }] });

    let bottomLetters = [...this.state.bottomLetters];
    bottomLetters.splice(id, 1);
    this.setState({ bottomLetters });
  };

  deleteLast = () => {
    if (!this.state.topLetters.length) return;

    const lastTopLetter = this.state.topLetters.length - 1;
    const lastLetter = this.state.topLetters[lastTopLetter].letter;

    let topLetters = [...this.state.topLetters];
    topLetters.pop();
    this.setState({ topLetters });

    let bottomLetters = [...this.state.bottomLetters];
    bottomLetters.push(lastLetter);
    this.setState({ bottomLetters });
  };

  render() {
    const { filledArray, topLetters, bottomLetters } = this.state;

    return (
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        <div style={{ marginBottom: '40px' }}>
          {filledArray.map((index, id, item) => (
            <button key={id} className='item'>
              {topLetters[id] && topLetters[id].letter}
            </button>
          ))}
        </div>
        <div>
          {bottomLetters.map((index, id, item) => (
            <button
              key={id}
              className='item'
              onClick={() => this.handleLetters2Click(item[id])}
            >
              {item[id]}
            </button>
          ))}
        </div>
        <button onClick={this.deleteLast} style={{ marginTop: '40px' }}>
          DELETE
        </button>
      </div>
    );
  }
}

export default myApp;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM