我站在一个棘手的情况。
我的reducer rhythmReducer.js如下:
import {TOGGLE_NOTE_VALUE} from '../constants/actionTypes';
import objectAssign from 'object-assign';
import initialState from './initialState';
export default function rhythmReducer(state = initialState.rhythm, action) {
let newState = objectAssign({}, state);
console.log("---RhythmReducer");
console.log(action.type);
switch (action.type) {
case TOGGLE_NOTE_VALUE:
console.log("TOGGLE_NOTE_VALUE");
return newState;
default:
return newState;
}
}
使用它的组件是RhythmContainer.js:
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/rhythmActions';
import {Meter} from './Meter';
export const RhythmContainer = (props) => {
let rows = [];
for (let i=0; i < props.rhythm.meters.length; i++) {
rows.push(<Meter key={i} actions={actions} rhythm= {props.rhythm.meters[i]}/>);
}
const handleClick = () => {
return props.store.dispatch(actions.toggleNoteValue);
};
return (
<div onClick={handleClick}>
This will be a 4/4 rhythm
{rows}
</div>
);
};
RhythmContainer.propTypes = {
rhythm: PropTypes.object.isRequired,
store: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
return {
rhythm: state.rhythm,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(RhythmContainer);
我的动作在rhythmActions.js中定义
import * as types from '../constants/actionTypes';
export function toggleNoteValue() {
console.log("toggleNoteValue");
return {type: types.TOGGLE_NOTE_VALUE};
}
即使reducer在页面初始化时运行,但是当我点击div时,我无法运行它。 toggleNoteValue()正在启动,但它永远不会进入实际的Reducer。 有什么帮助吗?
PS完整项目就在这里,以防它有所帮助:https://github.com/ichionid/rhythmGeneratorReact/tree/master/src
答案 0 :(得分:3)
以下是一些值得尝试的事情。
在您的项目中,configureStore.js
从中导入rootReducer
"../rootReducer"
,但没有这样的模块。我不确定这是不是
只是提交问题,但值得检查。
发送的参数应该是一个动作。 actions.toggleNoteValue
不是动作,它是一个返回动作的函数。尝试
props.store.dispatch(actions.toggleNoteValue())
或
而是props.actions.toggleNoteValue()
。
答案 1 :(得分:0)
有时候我会注意到,由于减速器未正确插入mapDispatchToProps
而无法点火时,会出现此问题:
// WRONG
import { action } from './actions'
// action will still fire as a function, but that's it
const Comp = ({ label }) => <button onClick={() => action()}>{label}<button>
export default connect(mapStateToProps, { action })
// RIGHT
import { action } from './actions'
// action is sent in as a prop meaning we use the connected version rather than the action directly
const Comp = ({ action, label }) => <button onClick={() => action()}>{label}<button>
export default connect(mapStateToProps, { action })