我正在尝试使用上下文将Redux存储传递给我的组件,而react-redux
提供了Provider。我这样做:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import eventsReducer from './GlobalReducer'; // <= IMPORTING
import './index.css';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<Provider store={createStore(eventsReducer)}>
<BrowserRouter>
<div>
<Route component={GlobalHeader} />
<Route component={GlobalFooter} />
</div>
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
我的reducer函数以这种方式声明:
import EventActions from './actions/EventActions';
class GlobalReducer {
eventsReducer = function(state = {},action) {
switch(action.type) {
case "LOAD_INITIAL_STATE":
return {...state, events: EventActions.load()};
default:
return state;
}
}
};
module.exports = GlobalReducer.eventsReducer;
碰巧我收到错误:
./ SRC / index.js
23:22-35“./GlobalReducer”中未找到“导出'默认'(导入为'eventReducer')
我甚至在这里尝试过箭头语法,但它没有帮助。
我尝试过多种方式写作:
1)使用
import GlobalReducer from './GlobalReducer';
然后写
<Provider store={createStore(GlobalReducer.eventsReducer)}>
然后错误更改为
错误:期望reducer成为一个函数。
2)使用
导出功能module.exports = GlobalReducer.eventReducer;
像
一样导入它import eventsReducer from './GlobalReducer';
然后将其用作
<Provider store={createStore(eventsReducer)}>
然后错误更改为
./ SRC / index.js
23:22-35“./GlobalReducer”中未找到“导出'默认'(导入为'GlobalReducer')
我甚至尝试将该功能从类中取出并使用module.exports
直接导出。它也不起作用!
我究竟做错了什么?这样做的正确方法是什么?
答案 0 :(得分:1)
将行module.exports = GlobalReducer.eventsReducer;
改为export default GlobalReducer.eventsReducer;
然后,使用以下内容导入:import eventsReducer from './GlobalReducer';
。
您不再使用GlobalReducer.eventsReducer
,而只是使用eventsReducer
。
答案 1 :(得分:1)
这通常是我构建项目的方式。请注意文件夹结构的更改。也许这对你也有用。
<强> index.js 强>
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducers from './reducers'; // <= IMPORTING
import './index.css';
import registerServiceWorker from './registerServiceWorker';
const store = createStore(reducers);
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<div>
<Route component={GlobalHeader} />
<Route component={GlobalFooter} />
</div>
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
<强> ./减速器/ index.js 强>
import { combineReducers } from 'redux';
import events from './events';
export default combineReducers({
events
});
<强> ./减速器/ events.js 强>
import EventActions from '../actions/EventActions';
export default (state = {}, action) => {
switch(action.type) {
case "LOAD_INITIAL_STATE":
return {...state, events: EventActions.load()};
default:
return state;
}
}