使用React在Redux中没有将操作传递给Reducer
我正在编写一个代码来使用redux应用主题。 这里是我的代码:使用React在Redux中没有将操作传递给Reducer
操作/ index.js
export const CHANGE_THEME = 'CHANGE_THEME';
export const changeTheme = (payload) => {
console.log('payload ' + payload)
return ({
type: CHANGE_THEME,
payload
})}
减速/ index.js
import { combineReducers } from 'redux'
import themeChangeHandler from './themeChangeHandler'
const rightBarMenuHandler = combineReducers({
themeChangeHandler
})
export default rightBarMenuHandler
themeChangeHandler.js
const themeChangeHandler = (state = 'light', action) => {
console.log('rec action ' + action.type)
switch(action.type) {
case 'CHANGE_THEME':
return action.payload
default:
return state
}
}
export default themeChangeHandler
事件使用菜单/ MenuItem
class AppBarRightButtonsMenu extends Component {
constructor(props) {
super(props);
}
onClickButton = (data) => {
this.props.dispatch(changeTheme('dark'))
}
render() {
const {onThemeChange, onLogout, dispatch} = this.props;
var i = 1;
if(NavigationButtonMenu) {
var list = NavigationButtonMenu.map((menuItem) => {
return <MenuItem key={i++} primaryText={menuItem.name} onClick = {this.onClickButton}/>;
});
return <Menu >{list}</Menu>;
} else {
return <div/>
}
}
}
export default connect()(AppBarRightButtonsMenu);
App.js
const App = ({theme}) => (
<SomeComp
theme={theme}
/>
function mapStateToProps(state) {
console.log('state.themeChangeHandler ' + state.themeChangeHandler)
return {
theme: state.themeChangeHandler === 'dark'?darkBaseTheme:customTheme,
};
}
export default connect(mapStateToProps, null) (App);
添加店
const store = createStore(reducers)
ReactDOM.render(<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
registerServiceWorker();
,我会在操作的控制台日志,但不是一个减速机(我上启动时减速的测试日志) 。我究竟做错了什么?
你如何设置你的商店?你已经“合并”了你的减速器,但你还没有联系到商店。
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
// create the store from the reducers
const store = createStore(combineReducers(/*...your reducers here...*/));
// You probably want to let your components have access to the store's state.
const AppWithStore = (
<Provider store={store}>
<App />
</Provider>
);
ReactDOM.render(<AppWithStore />, document.getElementById('whatever'));
一旦您完全设置完毕,您可以像访问App
组件一样访问商店状态。
您可以在React documentation的Redux绑定中找到有关Provider
组件的更多信息。
一旦您对此感到满意,我会建议您浏览Dan Abramov的优秀course on idiomatic Redux,其中提到了您可以使用商店和商店状态在首批视频中执行的一些技巧。
我已经做到了。忘了粘贴它。请检查。 –
控制台中是否有错误?你确定你正在合并减速器吗? 'combineReducers'函数需要一个对象。在你的情况下,它必须是'combineReducers({themeHandler})',以便在'themeHandler'键下可以访问状态。以下代码适用于我:https://gist.github.com/gkats/ad67323bc887c94d63982746bdbceed4 – gkats
问题是我正在使用Admin-On-Rest框架,并且必须将减法器添加到Admin组件。一旦我做到了,它的工作。感谢您的帮助 –
你在哪里创建了商店 –