首页 > 解决方案 > 我无法在 redux 存储中保存数组?

问题描述

在主屏幕中,我从 API 获取歌曲并将其保存在组件状态中,现在在我渲染歌曲之后,当我按下其中任何一个时,我调度一个动作以将所有歌曲保存在redux 状态并调度其他动作以显示底部播放器“真/假”我收到了这个错误

错误:操作必须是普通对象。使用自定义中间件进行异步操作

我不知道它为什么会出现,它只是我要保存的数组!

主屏幕

 _renderItem = ({item, index}) => {
    const {url} = this.state;
    return (
      <TouchableNativeFeed
        key={item.id}
        onPress={() => {
          console.log(
            'index-recent_tunes',
            index,
            this.state.recent_tunes,
          ); // I can see the output "array of songs" + index
          this.props.saveSongs(this.state.recent_tunes, index);
          this.props.isPlaying(true);
        }}
    .....
}


const mapDispatchToProps = dispatch => {
  return {
    isPlaying: _isPlaying => {
      dispatch(isPlayingAction(_isPlaying));
    },
    saveSongs: (songs, index) => {
      dispatch(songsInPlayerAction(songs, index));
    },
  };
};
export default connect(null, mapDispatchToProps)(Home);

还原

减速器

import {SONGS_IN_PLAYER} from '../actions/types';

let initialState = {
  allSongs: [],
  currentIndex: 0,
};

const songsInPlayerReducer = (state = initialState, action) => {
  switch (action.type) {
    case SONGS_IN_PLAYER:
      return {
        ...state,
        allSongs: action.songs,
        currentIndex: action.index,
      };
    default:
      return state;
  }
};

export default songsInPlayerReducer;

行动

import {SONGS_IN_PLAYER} from './types';

export const saveSongsPlayer = (songs, currentIndex) => {
  return {
    type: SONGS_IN_PLAYER,
    songs,
    currentIndex,
  };
};

店铺

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
};

const rootReducer = combineReducers({
   ....
  songsInPlayer: songsInPlayerReducer,
  ....
});

const persistedReducer = persistReducer(persistConfig, rootReducer);


export const store = createStore(
  persistedReducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
);
export const persistor = persistStore(store);

标签: javascriptreactjsreact-nativereduxreact-redux

解决方案


推荐阅读