我是新来的人,我正在尝试使用redux设置登录系统。在我的登录组件中,我将mapStateToProps
与connect
提供的react-redux
方法一起使用。
当我尝试从商店中获取所需物品时,它一直在说它是未定义的。这是我的登录组件的一个片段:
function mapStateToProps(state) {
return {
loggingIn: state.authentication.loggedIn,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(userActions, dispatch),
alertActions: bindActionCreators(alertActions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Login)
这是我尝试组合减速器的方法:
import { combineReducers } from 'redux';
import authentication from './userReducer';
import alert from './alertReducer'
const rootReducer = () => combineReducers({
authentication,
alert
});
export default rootReducer;
但是,我无法在Login组件中访问logginIn
道具。经过数小时的麻烦排除故障后,我通过删除箭头功能使其工作:
const rootReducer = combineReducers({
有人可以告诉我为什么箭头功能不起作用吗?谢谢
更新:这是我将根减速器导入index.js文件的方式
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk';
import rootReducer from './reducers'
const store = createStore(rootReducer, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'))
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
答案 0 :(得分:1)
docs告诉您调用CombineReducers以提供根减速器。 createStore方法需要一个减速器,而不是要获取该减速器的函数。
答案 1 :(得分:0)
除了Vinicius的答案外,您还可以重构您的combineReducers()
通话。
代替:
const rootReducer = () => combineReducers({
authentication,
alert
});
export default rootReducer;
我以前见过其他人做过,我个人认为编写清洁器所需的代码更少,只要它看起来不深奥,无论如何都可以这样写:
export default combineReducers({
authentication,
alert
});
您一次性导出并调用combineReducers()
。哦,要导入它,因为我们删除了rootReducer
,所以请执行以下操作:
import reducers from "./reducers";
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducers,
composeEnhancers(applyMiddleware(reduxThunk))
);