gpt4 book ai didi

javascript - 如何使用 JavaScript 编写 reducer 来操作此 JSON

转载 作者:行者123 更新时间:2023-12-04 10:50:07 24 4
gpt4 key购买 nike

我有一个这样的 JSON

"decks": [
{
"id": 65,
"name": "deck1",
"cards": [
{
"question": "q1",
"answer": "a1"
},
{
"question": "q2",
"answer": "a2"
},
{
"question": "q3",
"answer": "a3"
}
]
},
{
"id": 83,
"name": "deck2",
"cards": []
}

现在,我想在添加一张卡片后返回卡片对象
   {
"question": "q4",
"answer": "a4"
},

并且该卡应添加到相应的 ID 对于这种情况,假设 -65,结果应该像这样返回
"decks": [
{
"id": 65,
"name": "deck1",
"cards": [
{
"question": "q1",
"answer": "a1"
},
{
"question": "q2",
"answer": "a2"
},
{
"question": "q3",
"answer": "a3"
},
{
"question": "q4",
"answer": "a4"
}
]
},
{
"id": 83,
"name": "deck2",
"cards": []
}

这是我操作对象的 reducer 代码
case ADD_CARD:

var index = state.decks.findIndex(x => x.id === action.deckId);


return {
...state.decks,
decks: state.decks[index].cards.concat(action.newCard),
};

你能帮我写下正确的reducer代码吗?上面的代码没有给出预期的结果。
感谢您的时间和支持。

最佳答案

您的 state.decks是数组,因此您不能使用已使用的对象表示法覆盖数组项之一。还有一个小建议:我想说 Array.prototype.push()Array.prototype.concat() 更符合目的.

假设 decks不代表您的整个状态,您的尝试是在调度操作时更新状态:

{type:'ADD_CARD', deckId: 65, newCard:{question:'q4',answer:'a4'}}

您相应的 reducer 部分可能看起来像:
const appReducer = (state, action) => {
switch(action.type){
case ADD_CARD: {
const {deckId, newCard} = action,
{decks} = state,
index = decks.findIndex(({id}) => id === deckId)
decks[index]['cards'].push(newCard)
return {...state, decks}
}
default: return state
}
}

您可能会在现场演示下方找到概念证明

//dependency

const { createStore } = Redux

//default state, reducer, store

const defaultState = {"decks":[{"id":65,"name":"deck1","cards":[{"question":"q1","answer":"a1"},{"question":"q2","answer":"a2"},{"question":"q3","answer":"a3"}]},{"id":83,"name":"deck2","cards":[]}]},
appReducer = (state=defaultState, action) => {
switch(action.type){
case 'ADD_CARD': {
const {deckId, newCard} = action,
{decks} = state,
index = decks.findIndex(({id}) => id === deckId)
decks[index]['cards'].push(newCard)
return {...state, decks}
}
default: return state
}
},
store = createStore(appReducer)

//dispatchind 'ADD_CARD' action

store.dispatch({type:'ADD_CARD', deckId: 65, newCard:{question:'q4',answer:'a4'}})

//logging the updated store

console.log(store.getState())
.as-console-wrapper {min-height:100%}
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>

关于javascript - 如何使用 JavaScript 编写 reducer 来操作此 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522131/

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