最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - one redux action to manage multiple items - Stack Overflow

programmeradmin0浏览0评论

So I wanted to create a universal action creator to manage the items in redux store.

Let's say my redux store looks like this:

one: '',
two: '',
three: ''

My action creators looks like this:

export const setStatus = (name, status) =>{
    return function(dispatch){
        dispatch({
            type: 'SET_STATUS',
            name,
            status
        })
    }
}

and I don't know how to create an action that would manage all of it. Tried

case 'SET_STATUS':{
            return{
                ...state,
                action.name: action.status 
            }
        }

But redux won't let me. Is there any workaround?

So I wanted to create a universal action creator to manage the items in redux store.

Let's say my redux store looks like this:

one: '',
two: '',
three: ''

My action creators looks like this:

export const setStatus = (name, status) =>{
    return function(dispatch){
        dispatch({
            type: 'SET_STATUS',
            name,
            status
        })
    }
}

and I don't know how to create an action that would manage all of it. Tried

case 'SET_STATUS':{
            return{
                ...state,
                action.name: action.status 
            }
        }

But redux won't let me. Is there any workaround?

Share Improve this question edited Jun 6, 2018 at 18:18 zzzzBov 179k56 gold badges327 silver badges371 bronze badges asked Jun 6, 2018 at 18:14 MazMatMazMat 2,0943 gold badges15 silver badges27 bronze badges 1
  • 2 Possible duplicate of dynamic keys for object literals in Javascript – zzzzBov Commented Jun 6, 2018 at 18:18
Add a ment  | 

2 Answers 2

Reset to default 7

You should use bracket notation to use a variable as a key:

case 'SET_STATUS':{
    return{
        ...state,
        [action.name]: action.status 
    }
}

The think the code is usefull for you.Because you can change some data which you want.good luck

import { createStore } from 'redux'; 

const reducer = (state={
  one: '',
  two: '',
  three: ''
} , action)=>{
switch(action.type){
    case "SET_STATUS":
        state = {
            ...state,
            one: action.payload.one,
            two: action.payload.two,
            three: action.payload.three
        }
    break;
    default: break;
 }
 return state;
}


const store = createStore(reducer);

store.subscribe(()=>{
    console.log(store.getState());
});
const data = {
  one: 'value of one',
  two: 'value of two',
  three: 'value of three'
}
store.dispatch({ 
  type:"SET_STATUS",
  payload: data
});
发布评论

评论列表(0)

  1. 暂无评论