我正在编写我的第一个react原生应用程序。在这个应用程序中,聊天机器人,对话框使用int(比如intToFollow)递增,它跟踪显示了多少短语,每个短语在发送特定操作(通常是ACTION 1,有时是ACTION 2)后显示。在此之前一切都很好。
现在,当我试图实现另一个动作做其他事情,但需要操作intToFollow时,它告诉我我的int是undefined或NaN,我很困惑,因为对我来说,我的新reducer看起来和我的另一个reducer完全一样,它仍然工作得很好。我的问题是:同一个状态可以被多个reducer连续操纵吗?我错过了什么吗?
编辑说明:dialogFr和Eng是包含对象的数组,因此属性有时会在后面提到(像.steps),并且它们根据用户选择的语言有选择地使用. intToFollow的主要作用是作为每个数组的索引,并且每次按下某个按钮时都改变到下一个对象或者在增加了. steps的值后,它所到达的任何对象。这是没有问题的部分。ACTION 2的目的是做同样的事情,只是做了一个小的改变,即intToFollow的增量是固定的(这里是1),因为其他原因,我不能只使用ACTION 1!//编辑结束
import { createStore } from "redux";
import { dialogFr } from "../ressources/dialogsFrance";
import { dialogEng } from "../ressources/dialogsEng";
const initialState = {
isEnglish: true,
intToFollow: 0,
currentDialog: "a",
condition: false,
}
function reducer(state = initialState, action) {
let nextState
switch (action.type) {
case 'ACTION_1':
const intToFollow = state.intToFollow;
nextState = {
...state,
intToFollow: intToFollow + dialogFr[intToFollow].steps,
currentDialog: state.isEnglish ? dialogEng[intToFollow] : dialogFr[intToFollow],
}
return nextState || state
case 'ACTION_2':
const condition = state.condition;
if (condition === true) {
nextState = {
...state,
intToFollow: intToFollow + 1,
currentDialog: state.isEnglish ? dialogEng[intToFollow] : dialogFr[intToFollow],
}
return nextState || state
}
default:
return state
}
}
const store = createStore(reducer, initialState)
export default store
我的问题是dialogEng[intToFollow]和dialogFr[intToFollow]在ACTION2中被认为是undefined,但在ACTION1中却可以正常工作
使用console.log,我发现intToFollow作为NaN进入第二个reducer,因此呈现出对话框数组Undefined。然而,这个商店是唯一定义和操作inToFollow的地方,所以我花了几个小时看同样的10行代码...这就是我所得到的!
1条答案
按热度按时间5w9g7ksd1#
当action.type === ACTION_2时,代码变为:
intToFollow
在哪里声明?你只在ACTION_1中声明了它。
您应该:
1.在交换机外声明
1.也在ACTION_2中声明它
1.或者将
intToFollow: intToFollow + 1,
和currentDialog: state.isEnglish ? dialogEng[intToFollow] : dialogFr[intToFollow]
分别更改为intToFollow: state.intToFollow + 1,
和currentDialog: state.isEnglish ? dialogEng[state.intToFollow] : dialogFr[state.intToFollow],
。