[英]redux - how to store and update a key/value pair
I am using redux wth reactjs. 我正在使用redux wth reactjs。
I want to store simple key/value pairs but can't get the reducer syntax right. 我想存储简单的键/值对,但无法正确获得reducer语法。
In this case each key/value pair will hold a connection to an external system. 在这种情况下,每个键/值对将保持与外部系统的连接。
Is this the right way to do it? 这是正确的方法吗? I'm at the beginning with redux so it's a bit of mystery.
我正在开始使用redux,所以它有点神秘。
export default (state = {}, action) => {
switch(action.type) {
case 'addConnection':
return {
connections: {
...state.connections, {
action.compositeKey: action.connection
}
}
default:
return state
}
}
You just have a couple mistakes with {}
instead of []
and forgetting to use Object.assign
. 你只有
{}
而不是[]
的一些错误而忘记使用Object.assign
。
const reducer = (state = {}, action) => {
switch (action.type) {
case 'addConnection':
return Object.assign({}, state, {
connections: [
...state.connections,
{
[actions.compositeKey]: action.connection
}
]
});
default:
return state;
}
}
export default reducer;
It might help to see it expressed this way too. 看来它也表达了这种方式可能会有所帮助。 It does the same thing but I think it reads a little nicer
它做同样的事情,但我认为它看起来更好一点
const reducer = (state = {}, {type, compositeKey, connection}) => {
switch (type) {
case 'addConnection':
return Object.assign({}, state, {
connections: state.connections.concat({
[compositeKey]: connection
})
});
default:
return state;
}
}
export default reducer;
Or if you're using Immutable , something like this 或者,如果你使用的是Immutable ,就像这样
import Immutable from 'immutable';
const reducer = (state = Immutable.Map(), {type, compositeKey, connection}) => {
switch (type) {
case 'addConnection':
return state.set(
'connections',
state.get('connections').concat({
[compositeKey]: connection
})
);
default:
return state;
}
}
export default reducer;
This worked for me: 这对我有用:
export default (state = {}, action) => {
switch(action.type) {
case 'addConnection':
return {
...state,
connections: {
...state.connections,
[action.compositeKey]: action.connection
}
}
default:
return state
}
}
From the docs: 来自文档:
https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#correct-approach-copying-all-levels-of-nested-data https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#correct-approach-copying-all-levels-of-nested-data
This may work 这可能有效
const reducer = (state = {}, {type, compositeKey, connection}) => {
switch (type) {
case 'addConnection':
var newData={};
newData[compositeKey]=connection;
return Object.assign({}, state, newData)
});
default:
return state;
}
}
export default reducer;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.