gpt4 book ai didi

javascript - 使用函数作为值来更改 ReactJS 中的状态

转载 作者:行者123 更新时间:2023-11-29 18:47:01 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com