我的意图是做一些非常基本的事情。我只是希望我的名字在渲染时出现在 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);
我猜测罪魁祸首是在我设置初始状态的 reducer 中。初始状态是否设置得不够早?这部分代码看起来正确吗?
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;
}
}
这是我设置初始状态文件的方式:
export default {
hello: {
name: 'Gabriel'
}
};
而且,我组合 reducer 的方式:
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;
应用程序的其他容器/组件运行良好,但只有这个新容器无法正常工作。我正在使用 react slingshot boilerplate 。刚刚添加了一条额外的路线。我复制了样板中的结构。
最佳答案
“name”的初始状态在对象“hello”的第二层定义。
因此要访问它,您需要将 mapStateToProps 函数更改为:
function mapStateToProps(state) {
return {
name: state.hello.name
};
}
关于reactjs - 失败的 PropType。值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43414697/