我的目的是做一些非常基本的事情。我只希望我的名字在渲染时出现在 HelloPage 容器中,然后通过单击将我的名字变成“Bob”。我想我错过了一些愚蠢的东西。
HelloPage.js(容器,我的名字应该出现在其中,但完全未定义)
import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/helloActions';
export const HelloPage = ({name, actions}) => {
return (
<div>
My name is {name}. This is the hello page.
<div onClick={() => actions.sayHello()}>But my name could be different.</div>
</div>
);
};
HelloPage.propTypes = {
actions: PropTypes.object.isRequired,
name: PropTypes.string.isRequired
};
function mapStateToProps(state) {
return {
name: state.name
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(HelloPage);
我猜罪魁祸首在我设置初始状态的减速器中。初始状态是否设置得不够早?这部分代码看起来对吗?
import { SAY_HELLO } from '../constants/actionTypes';
import objectAssign from 'object-assign';
import initialState from './initialState';
export default function helloReducer(state = initialState.hello, action) {
switch (action.type) {
case SAY_HELLO:
return objectAssign({}, state, { name: "Bob" });
default:
return state;
}
}
这是我设置 initialState 文件的方式:
export default {
hello: {
name: 'Gabriel'
}
};
而且,我组合减速器的方式:
import { combineReducers } from 'redux';
import fuelSavings from './fuelSavingsReducer';
import hello from './helloReducer';
import {routerReducer} from 'react-router-redux';
const rootReducer = combineReducers({
fuelSavings,
hello,
routing: routerReducer
});
export default rootReducer;
该应用程序的其他容器/组件运行良好,但只是这个新容器不是。我正在使用反应弹弓样板。只是增加了一条额外的路线。我复制了样板文件中的结构。