重用Reducer Logic不会使用Redux和React来切换对象

时间:2017-02-27 07:19:36

标签: reactjs redux

我正在为两个不同的事件重用相同的reducer逻辑。我们的想法是根据您点击的文本切换班级。每个事件都会触发,但我的目标不是切换。有什么想法吗?

App:

import React from "react"
import { bindActionCreators } from 'redux'
import { connect } from "react-redux"
import * as toggleactionCreators from '../actions/toggleActions';

function mapStateToProps(state) {
  return {
    hiddenA: state.toggleA.hidden,
    hiddenB: state.toggleB.hidden
  }
}

function mapDispachToProps(dispatch) {
  return bindActionCreators({...toggleactionCreators}, dispatch)
}

class Main extends React.Component {

  toggleDiv() {
    this.props.toggleDiv();
    console.log(this.props)
  }

  render() {
    const { hiddenA, hiddenB } = this.props;
    return (
      <div>
      <div>
        <h3 onClick={this.toggleDiv.bind(this)} className={ hiddenA ? null : "toggled"} >Good Day!</h3>
        <h1 onClick={this.toggleDiv.bind(this)} className={ hiddenB ? null : "toggled"} >Hello There!</h1>
      </div>
    </div>
    )    
  }
}

export default connect(mapStateToProps, mapDispachToProps)(Main);

Index Reducer:

import { combineReducers } from "redux"
import toggle from "./toggleReducer"

function createNamedWrapperReducer(reducerFunction, reducerName) {
  return (state, action) => {
      const {name} = action;
      const isInitializationCall = state === undefined;
      if(name !== reducerName && !isInitializationCall) return state;
      return reducerFunction(state, action);    
  }
}
const thereducer = combineReducers({
    toggleA : createNamedWrapperReducer(toggle, 'A'),
    toggleB : createNamedWrapperReducer(toggle, 'B'),
});

export default thereducer;

toggleReducer:

const toggle = (state = { hidden: true}, action) => {
  switch(action.type) {
    case 'TOGGLE_DIV':
      return Object.assign({}, ...state, {hidden: !state.hidden});
    default:
      return state;
  }
};
export default toggle;

按压式:

export const toggleDiv = () => {
  return {
    type: 'TOGGLE_DIV',
  }
}

1 个答案:

答案 0 :(得分:0)

这就是我调试它的方法。

  1. 为您的浏览器下载Redux DevTools。这是Chrome的网址:https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd

  2. 为您浏览器下载React devtools。这是Chrome的网址:https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi

  3. 查看Redux Devtools:

    • 是您的动作创建者发出的动作
    • reducer是否正确更新状态?
  4. 如果两个操作和reducers看起来都正确,请检查您的React组件:

    • 组件是否收到正确的道具?如果是,那就是道具的呈现方式。如果不是,那就是商店如何连接到您的组件。
  5. 希望这个调试教程对您有用。如果您有任何后续问题,请不要犹豫,问:)