我正在尝试向我的应用程序列表上的按钮添加功能,以便单击UP时,列表项与直接位于其顶部的项目交换。

我尝试在setState中使用函数作为状态的值。但是当我单击按钮时,发生此错误:

TypeError: Cannot read property 'map' of undefined
App.render
src/App.js:49
  46 | return(
  47 |   <div>
  48 |     <h1>UNUM Challenge</h1>
> 49 |     <ol>
     | ^  50 |       {this.state.shoppingList.map((item, index) =>
  51 |          (<li data-index = {index} key={index}>
  52 |             {item}


这是怎么回事这样设置状态时,不能使用函数作为值吗?

this.setState({
        shoppingList: arraymove(shoppingList, currentIndex , currentIndex - 1)
})


这是完整的代码:

import React, { Component } from 'react';

function arraymove(arr, fromIndex, toIndex) {
        var element = arr[fromIndex];
        arr.splice(fromIndex, 1);
        arr.splice(toIndex, 0, element);
    }

    class App extends React.Component {
        constructor(props){
        super(props);

        this._handleItemSort = this._handleItemSort.bind(this);

        this.state = {
            shoppingList: ['Bananas', 'Apples', 'Rice', 'Eggs' , 'GTX 1080Ti', 'Avocado']
        }
      }



      _handleItemSort(dir, currentIndex) {
        // create new list of items from a spread of our current shoppingList state.
        // we don't want to reference the actual state and mutate it! 😱
        const shoppingList = [...this.state.shoppingList]

        if (dir === "up" ){
          this.setState({
            shoppingList: arraymove(shoppingList, currentIndex , currentIndex - 1)
          })
        }

      }

      render() {
        return(
          <div>
            <h1>UNUM Challenge</h1>
            <ol>
              {this.state.shoppingList.map((item, index) =>
                    (<li data-index = {index} key={index}>
                    {item}
                    <div className='controls'>
                      <button
                        disabled={index === 0}
                        onClick={ () => this._handleItemSort("up", index) }>UP</button>
                      <button
                        disabled={this.state.shoppingList.length === index + 1}
                        onClick={ () => this._handleItemSort("down", index) } >DOWN</button>
                    </div>
                  </li>)
                )}
            </ol>
          </div>
        );
      }
    }

最佳答案

返回arr.splice()将为您提供一个包含已删除元素的数组。如果仅删除一个元素,则返回一个元素的数组。如果没有删除任何元素,则返回一个空数组。

您需要返回修改后的数组,如下所示:

function arraymove(arr, fromIndex, toIndex) {
  var element = arr[fromIndex];
  arr.splice(fromIndex, 1);
  arr.splice(toIndex, 0, element);
  return arr;
}

07-27 14:45