Redux initialState将数据附加到现有密钥中

问题描述 投票:0回答:2

我尝试了很多事情,但没有达到想要的。我在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密钥。

我希望有人帮助我。

编辑:Working Example

reactjs redux immutability
2个回答
2
投票
 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;

1
投票

Reducer用于更新状态,而不是从状态获取数据。

GET_LIST操作返回state.coins,这会破坏状态对象,从而返回错误的值

使用store.getState()从商店获取数据

© www.soinside.com 2019 - 2024. All rights reserved.