Redux initialState 将数据附加到现有密钥中
Redux initialState append data into existing key
我尝试了很多东西,但我无法实现我想要的。我在 redux 中有一个 initialState。它有 4 个硬币名称,如下所示。我正在尝试用 API 中的值填充此键。但最后我只有 1 个带数据的密钥。
import { SET_LIST, GET_LIST } from '../actions'
const initialState = {
coins: {
'BTC': {},
'ETH': {},
'LTC': {},
'DOGE': {},
},
loading: false,
error: null
}
const coinsReducers = (state = initialState, action) => {
switch (action.type) {
case SET_LIST: {
const key = action.payload.key;
const list = action.payload.list;
let obj = Object.assign({}, state);
obj.coins[key] = list;
obj.loading = true;
return obj;
}
default: return state;
}
}
export default coinsReducers
我在 app.js componentDidMount
钩子中迭代这个初始状态并使用键进行 api 调用。当我使用 BTC 密钥进行 api 调用时,我想将响应推送到 BTC 密钥中。
希望有人帮助我。
reducer 用于更新状态,而不是从中获取数据。
GET_LIST
操作 returns state.coins
破坏状态对象,从而返回错误值
使用 store.getState() 从存储中获取数据
case SET_LIST: {
const {key, list} = action.payload;
return { ...state, loading: true, coins: {...state.coins, [key]: list }};
}
case GET_LIST:
// don't sure what you try to achieve here, anyhow what you are saying is that
// from now on all the state of the app it just state.coins
return state.coins
default: return state;
我尝试了很多东西,但我无法实现我想要的。我在 redux 中有一个 initialState。它有 4 个硬币名称,如下所示。我正在尝试用 API 中的值填充此键。但最后我只有 1 个带数据的密钥。
import { SET_LIST, GET_LIST } from '../actions'
const initialState = {
coins: {
'BTC': {},
'ETH': {},
'LTC': {},
'DOGE': {},
},
loading: false,
error: null
}
const coinsReducers = (state = initialState, action) => {
switch (action.type) {
case SET_LIST: {
const key = action.payload.key;
const list = action.payload.list;
let obj = Object.assign({}, state);
obj.coins[key] = list;
obj.loading = true;
return obj;
}
default: return state;
}
}
export default coinsReducers
我在 app.js componentDidMount
钩子中迭代这个初始状态并使用键进行 api 调用。当我使用 BTC 密钥进行 api 调用时,我想将响应推送到 BTC 密钥中。
希望有人帮助我。
reducer 用于更新状态,而不是从中获取数据。
GET_LIST
操作 returns state.coins
破坏状态对象,从而返回错误值
使用 store.getState() 从存储中获取数据
case SET_LIST: {
const {key, list} = action.payload;
return { ...state, loading: true, coins: {...state.coins, [key]: list }};
}
case GET_LIST:
// don't sure what you try to achieve here, anyhow what you are saying is that
// from now on all the state of the app it just state.coins
return state.coins
default: return state;