javascript - 在 ReactJS 中使用函数作为值来改变状态

标签 javascript reactjs

我正在尝试向应用程序列表上的按钮添加功能,以便当单击 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;
}

关于javascript - 在 ReactJS 中使用函数作为值来改变状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011057/

相关文章:

php - PHP + JS的模板引擎但是

javascript - Bootstrap 3,在一行产品后插入一个div

javascript - Soundmanager 2,无论我尝试什么,我都无法设置 SWF 路径

javascript - 两个数字变量相加返回 NaN

javascript - 使用 shouldComponentUpdate 来打破状态设置循环?

reactjs - WebStorm 中未使用的导出默认值

javascript - 如何自定义 Material UI 选项卡、选项卡滚动条

javascript - 如何在箭头函数中进行条件渲染?

Javascript (Vue.js) - 将表行添加到 DOM 中的错误节点

reactjs - 如何在 React with Material-UI 中垂直和水平居中?