我正在尝试使用React和Redux的示例。我可以看到呼叫进入我的减速机并返回。但是不调用容器内的mapStateToProps。以下是代码段。
Container
--------------
import React from 'react';
import ReactDOM from 'react-dom';
import {loadCaseTypes} from '../../actions/caseAction';
import { connect } from 'react-redux';
import CaseSearchComponent from './CaseSearchComponent';
import configureStore from '../../store/configureStore';
const store = configureStore();
export class CaseSearchContainer extends React.Component {
componentDidMount() {
store.dispatch(loadCaseTypes());
}
render() {
return(<CaseSearchComponent/>);
}
}
function mapStateToProps(state) {
alert('mapstatetoprops');
return {caseTypes: state.caseTypes}
}
function mapDispatchToProps(dispatch) {
return {
getCaseTypes: dispatch(loadCaseTypes)
}
}
export default connect(mapStateToProps, mapDispatchToProps)
(CaseSearchContainer);
Reducer
-------
let cases = [];
export default function caseReducer(state = {}, action) {
switch(action.type) {
case constants.LOAD_CASES_SUCCESS:
return state;
case constants.LOAD_CASE_TYPES_SUCCESS:
const newState = Object.assign({}, state, {caseTypes:action.caseTypes});
alert(state.caseTypes)
return newState;
default:
return state;
}
}
调用Reducer中的警告,但调用不会进入容器内的mapStateToProps。我在代码中遗漏了什么吗?
答案 0 :(得分:0)
从reducer使用mapStateToProps
到获取状态。您可以通过this.props.caseTypes
在reducer中使用mapDispatchToProps
更改状态。通过this.props.getCaseTypes()
访问Accesseble(也许getCaseTypes在这里令人困惑,最好使用setCaseTypes或changeCaseTypes)
Container的常规模型
import....
const mapStateToProps = state => {
return {
caseTypes: state.caseTypes,
};
};
const mapDispatchToProps = dispatch => {
return {
setCaseTypes: () => dispatch(loadCaseTypes())
};
};
class CaseSearchContainer extends React.Component {
....
render() {
return <CaseSearchComponent/>;
}
};
const ConnecteContainer = connect(mapStateToProps, mapDispatchToProps)
(CaseSearchContainer);
export default ConnectedContainer;
在reducer中声明一个初始状态并保持不变:
const state = {
caseTypes: 'some case types'
};
export default (state, action) => {
switch (action.type) {
case SOME_ACTION:
return (...state, caseTypes: 'new case types')
}
}