简体   繁体   English

使用输入更新React.js中的Redux状态

[英]Update redux state in reactjs with input

In my application i am displaying person data. 在我的应用程序中,我正在显示人员数据。 I have a scenario where I can input new person. 我有一个可以输入新人的场景。 So far I have got this: Reducer: 到目前为止,我已经知道了:Reducer:

export default function (state = [], action) {
    console.log("Reducing");
    switch (action.type) {
        case 'ADD':
            console.log("ADDING!");
            return action.payload;
            break;
    }
    return state;
}

Action: 行动:

export const addPerson = (person) => {
    console.log("addPerson Action Fired! ", person);
    return {
        type: 'ADD',
        payload: person
    }
};

I have a reducer with few person data which i am showing in my application but i am blocked at this point of adding new person. 我在我的应用程序中显示的reducer包含很少的人数据,但是在添加新人时被阻止。 So far i can see my input in console log but can't figure out how can i add it to the state. 到目前为止,我可以在控制台日志中看到我的输入,但无法弄清楚如何将其添加到状态中。 Help would be very much appreciated. 帮助将不胜感激。

This is the reducer where i am showing the data from. 这是我从中显示数据的减速器。

export default function () {
    return ["abc","def","ghi","jkl"]
}

Now i am displaying a list of these elements from the array(each are one person). 现在,我正在显示数组中这些元素的列表(每个都是一个人)。 When i add one it will be added with these persons and show me the updated list. 当我添加一个时,将与这些人一起添加并向我显示更新的列表。

You should do the following in your reducer: 您应该在减速器中执行以下操作:

export default function (state = [], action) {
    console.log("Reducing");
    switch (action.type) {
      case 'ADD':
        return [
          ...state,
          action.payload,
        ]
    }
    return state;
}

In this way, you add the person to your existing array. 这样,您可以将该人添加到现有阵列中。 Otherwise you changes your current state value from an array to an object. 否则,您会将当前state值从数组更改为对象。


Let's consider your person object value is the following and you dispatch it: 让我们考虑您的人员对象值如下,然后分派它:

{
  type: 'ADD',
  payload: {
    id: 1,
    name: 'John Doe',
  }
}

With your previous code, you would have the current value: 使用先前的代码,您将获得当前值:

// First step
return action.payload;

// Second step
return { id: 1, name: 'John Doe' };

With the corrected code: 使用更正的代码:

// First step
return [
  ...state,
  action.payload,
]

// Second step
return [
  ...[],
  { id: 1, name: 'John Doe' },
]

// Third step
return [{ id: 1, name: 'John Doe' }];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM