如何解决此错误“ combineReducers”是只读的。在react-native / react-redux中

时间:2019-04-30 07:23:29

标签: react-native react-redux

我正在使用redux在react-native中创建一个新的todo应用。 使用CombineReducers设置rootReducer时,出现以下错误。

“ combineReducers”是只读的。

"combineReducers" is read-only.

// reducers/todos.js

let nextId = 0;
const todos = (state = [], action) => {
    switch (action.type) {

        case 'ADD_TODO':

            return [
                ...state, {
                    id: nextId++,
                    text: action.text,
                    completed: false,
                }
            ]

        case 'TOGGLE_TODO':
            return state.map(todo =>
                (todo.id === action.id) ? { ...todos, completed: !todo.completed } : todo)

        default:
            return state
    }
}
export default todos;

创建了可见性过滤器以切换待办事项状态。


// reducers/visibilityFilter.js

const visibilityFilter = (state='SHOW_ALL', action) =>{
    return state;
}

export default visibilityFilter;

将两个reducer合并到索引文件中。

// reducers/index.js 

import { combineReducers } from 'redux';

import todos from './todos';
import visibilityFilter from './visibilityFilter';

export default combineReducers = combineReducers({
    todos,
    visibilityFilter
})

这是我的商店文件

import { createStore } from 'redux';

import rootReducer from '../reducers';

export default store = createStore(rootReducer);

2 个答案:

答案 0 :(得分:1)

如消息中明确指出的那样,不允许您重新分配asyncio.Future。只需将您的代码更改为以下内容即可,如the docs中所述:

combineReducers

答案 1 :(得分:0)

你为什么这样子?

export default combineReducers = combineReducers({
    todos,
    visibilityFilter
})

combineReducers()的编写方式如下:

import { combineReducers } from "redux";

export default combineReducers({
  todos: () => {
    return {};
  }
});

鉴于尝试并记住一个reducer必须始终返回一个对象,字符串或数字,这是开始使用Reducer的最低要求,以确保您的应用程序不会中断并且您可以获取一些内容进入屏幕。

此外,您不一定需要将combineReducers()标识为rootReducer,您可以像这样将其组合在一起:

import { createStore, compose, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducers from "../reducers";

const store = createStore(reducers, {}, compose(applyMiddleware(thunk)));

export default store;

最后,创建store后,您需要将其导入回到App.js并使用Provider标签将其连接起来,例如:

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import {
  createBottomTabNavigator,
  createStackNavigator,
  createAppContainer
} from "react-navigation";
import { Provider } from "react-redux";

import store from "./store";

并且:

export default class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <View style={styles.container}>
          <MainNavigator />
        </View>
      </Provider>
    );
  }
}