React Native Redux createStore error:undefined is

2019-09-07 20:16发布

问题:

I'm use Redux with ReactNative,I'd like to create a store with reducer

And,I got error below, point to line 'switch (action.type)' in function switchToTab() in reducer.js

undefined is not an object(evaluating 'action.type')

Here is my actions.js

export const SWITCH_TAB = 'switchTab'

export function switchTab(index) {

return {
    type: SWITCH_TAB,
    index: index
}

}

Here is my reducer.js

import { SWITCH_TAB } from './actions.js'

export function switchToTab(state = {}, action) {

switch (action.type) {//error point to this line

    case SWITCH_TAB:
        return Object.assign({}, ...state, {
            index: action.index
        });
    break;

    default:
        return state;
}

}

Here is createStore:

import { createStore } from 'redux';
import { switchToTab } from './reducer.js'

export default class MainPage extends Component {
    constructor(props) {
    super(props);
    this.state = {
        index:0
    };

    let store = createStore(switchToTab());
}

回答1:

You dont call the reducer when you create the store. createStore accepts a reducer function as its first argument.

import { createStore } from 'redux';
import { switchToTab } from './reducer.js'

export default class MainPage extends Component {
    constructor(props) {
    super(props);
    this.state = {
        index:0
    };

    let store = createStore(switchToTab); // dont call this here, just pass it
}