在Redux-React Native中使用reducer时导入/导出

时间:2018-11-13 03:09:19

标签: javascript reactjs react-native redux

我正在使用React Native研究Redux,我有一个这样的例子:


reducer.js

import {combineReducers} from "redux"; 
import {HomeReducer as home} from "../routes/Home/modules/home";

const makeRootReducer = () => {
    return combineReducers({
        home
    });
};

export default makeRootReducer;

createStore.js

import {createStore, applyMiddleware, compose} from 'redux';
import thunk from "redux-thunk";
import {createLogger} from 'redux-logger';

import makeRouteReducer from './reducer';

const log = createLogger({diff: true, collapsed: true});

export default (initialState = {}) => {
    const middleware = [thunk, log];
    const enhancers = [];

    return store = createStore(
        makeRouteReducer(),
        initialState,
        compose(
            applyMiddleware(...middleware),
            ...enhancers
        )
    );
}

它工作正常,但我不明白为什么必须在 reducer.js 中使用export default

当我尝试使用

// reducer.js
export makeRootReducer

// createStore.js
import {makeRouteReducer} from './reducer';

没有用。

请详细解释以帮助我。

非常感谢您。

1 个答案:

答案 0 :(得分:2)

您正在谈论命名出口默认出口 ...

命名导出示例:

export const someFunction = () => {
   // some code here...
}

现在您可以将其导入到另一个文件中,如下所示:

import {someFumnction} from './nameOfFile'

但是,如果您这样做:

export default function someFunction () {
   // some code here...
}

这是默认导出,您必须像这样导入它:

import someFunction from './nameOfFile'

在您的示例中,如果您对此进行更改:

const makeRootReducer = () => {
    return combineReducers({
        home
    });
};

export default makeRootReducer;

对此:

export const makeRootReducer = () => {
    return combineReducers({
        home
    });
};

它将成为命名出口,而不是默认出口,现在您可以执行以下操作:

import {makeRootReducer} from....

希望可以澄清...还有更多info