如何在react -native中更改/更新redux中存储的值

时间:2019-10-10 09:39:02

标签: react-native redux react-redux

我正在使用redux将用户数据(例如他的姓名,用户ID,用户图像和用户电子邮件)存储在redux中。 减速器是

const initialState = {
  user: []
};
function rootReducer(state = initialState, action) {

  if (action.type === 'ADD_USER') {
    return Object.assign({}, state, {
      user: state.user.concat(action.payload)
    });

  }
  if (action.type === 'REMOVE_USER') {
    //return Object.assign({}, initialState)
    return {
      ...state,
      user : []
    }

  }
  if (action.type === 'CHANGE_USER') {

     state.user.splice(0)

    return Object.assign({}, state, {
      user: state.user.concat(action.payload)
    });

  }


  return state;
};
export default rootReducer;

要添加我要像这样调度的用户

 let user_id = response[0][1]
          let user_name = response[1][1]
          let user_image = response[2][1]
          let email = response[3][1]

            this.props.add({ user_id, user_name, user_image, email });

现在假设我想更改电子邮件或用户名,那么我如何更改/更新特定字段(例如电子邮件)? 目前我正在这样做

this.props.change({ user_id : 1, user_name : 'sdfd', user_image:'', email:'abc@gmail.com' });

这将通过一个动作CHNAGE_USER 在上述行之后,我正在致电

let a = JSON.stringify(this.props.user)
  console.log("val-----------",a)

我的意思是更新数据后,我试图获取最新信息,但这给了我空数组

val----------- []

请告诉我两种更改整个对象以及更改特定字段(例如电子邮件)的方法吗? 谢谢,谢谢!

2 个答案:

答案 0 :(得分:1)

在redux文档中,您可以在状态数组中找到inserting/removing/updateing项的食谱。

答案 1 :(得分:0)

!!!这是在Redux中存储“仅一个用户”的数据的示例 如果您有很多用户要存储,这将无法正常工作!

    const initialState = {
        user: {  }
    };
    function rootReducer(state = initialState, action) {
        switch (action.type) {
            case "ADD_USER":
                return {
                    ...state,
                    user: action.payload
                };
            case "REMOVE_USER":
                return {
                    ...state,
                    user: {}
                };

            case "UPDATE_USER":
                /* so you return a new state object with all the data from old state
                user also contain the data from old state.user but you update some of his parameters
                like this.props.updateUser({  email:'abc@gmail.com' }); update only email field 
                this.props.updateUser({   user_name : 'sdfd' , email:'abc@gmail.com' }); update only user_name field

                change the name of action too, because later you will add more item in the redux and "change" dont say it change what ( just an idea )
                */
                return {
                    ...state,
                    user: {
                    ...state.user,
                    ...action.payload
                    }
                };

            default: return state;
        }
    }
    export default rootReducer;