gpt4 book ai didi

javascript - 根据索引 react redux更新数组

转载 作者:行者123 更新时间:2023-11-30 19:44:16 25 4
gpt4 key购买 nike

我正在使用 React 学习 redux。我正在尝试根据单击按钮更新一组数字。我特别想根据导入的 json 文件更新特定索引处的计数器。

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { upVote, downVote } from '../store/actions/voteAction';

class Voter extends Component {
render() {
const { count, upVote, downVote, id} = this.props
return (
<div>
<button onClick={() => upVote(id)}>+</button>
The count is {count[id]}
<button onClick={() => downVote(id)}>-</button>
</div>
)
}
}

const mapDispatchToProps = dispatch => ({
upVote: (payload) => dispatch(upVote(payload)),
downVote: (payload) => dispatch(downVote(payload))
});

const mapStateToProps = (state) => ({
count: state.vote.count

})
export default connect(mapStateToProps, mapDispatchToProps)(Voter);

我认为我的问题在于我如何在我的 reducer 中传递和更新有效负载。

import {UP_VOTE,DOWN_VOTE} from '../actions/actionTypes'
import Mice from './../../imports/mice'
const initialState = {
count: new Array(Mice.length).fill(0)
}


const voteReducer = (state=initialState, action) => {
const id = action.payload
switch(action.type){
case UP_VOTE:
return{
...state, count: state.count[id] + 1
}
case DOWN_VOTE:
return{
...state, count: state.count[id] - 1
}
default:
return state
}

}

export default voteReducer;

我更新了数组,但每个索引仍在变化,看来我仍在改变 count 数组而不是其中的索引。

我已将所有代码上传到 CodeSandbox 以供查看和试验: CodeSandbox Link

感谢阅读

最佳答案

使用map方法创建一个新数组,添加改变一个元素。 Redux 开关将是:

switch (action.type) {
case UP_VOTE:
return {
...state,
count: state.count.map((vote, i) => (i === id ? vote + 1 : vote))
};
case DOWN_VOTE:
return {
...state,
count: state.count.map((vote, i) => (i === id ? vote - 1 : vote))
};
default:
return state;
}

工作代码在这里 https://codesandbox.io/s/74pmomo42j

关于javascript - 根据索引 react redux更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55083827/

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