使用React未将操作传递给Redux中的Reducer

时间:2017-10-05 07:00:06

标签: reactjs react-redux

我正在编写一个使用redux应用主题的代码。 这是我的代码:

操作/ 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

事件正在使用Menu / 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();

我只是在操作中获取控制台日志,而不是在reducer中获取控制台日志(我在启动时获得reducer的测试日志)。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您如何设置商店?你已经&#34;合并了#34;你的减速机,但你还没有连接到商店。

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,其中提到了你可以在商店和商店状态的第一个视频中做一些技巧