您可以使用dispatch
而不通mapDispatchToProps
,或者您可以使用mapDispatchToProps
注入的道具,而不是使用dispatch
。這就是爲什麼mapDispatchToProps
這樣調用 - 它可以讓你定義一些基於dispatch
的其他道具,所以你不需要再次使用它。
這是一個使用mapDispatchToProps
方法的例子。您可能會發現代碼here。
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { toggleQuestionModal, toggleConfirmation } from '../actions/questionActions';
import QuestionModal from '../components/questionModal';
class QuestionPage extends Component {
constructor(props, context) {
super(props, context);
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.afterOpenModal = this.afterOpenModal.bind(this);
}
openModal() {
this.props.toggleQuestionModal(true);
}
afterOpenModal() {
// references are now sync'd and can be accessed.
// this.subtitle.style.color = '#f00';
}
closeModal() {
this.props.toggleConfirmation(true);
}
render() {
const { modalIsOpen } = this.props;
return (
<div>
<QuestionModal modalIsOpen={modalIsOpen} openModal={this.openModal} closeModal={this.closeModal}
afterOpenModal={this.afterOpenModal} />
</div>
);
}
}
QuestionPage.propTypes = {
modalIsOpen: PropTypes.bool.isRequired,
toggleQuestionModal: PropTypes.func.isRequired,
toggleConfirmation: PropTypes.func.isRequired
};
function mapStateToProps(state, ownProps) {
return {
modalIsOpen: state.question.modalIsOpen
};
}
function mapDispatchToProps(dispatch) {
return {
toggleQuestionModal: bindActionCreators(toggleQuestionModal, dispatch),
toggleConfirmation: bindActionCreators(toggleConfirmation, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(QuestionPage);
這是推薦的方法。當你將mapDispatchToProps
傳遞給connect
幫手時,你的動作就會被綁定到道具上。因此,您可以使用this.props.yourAction
來調用它。
另一種方法是直接將動作分派給商店。你可以這樣做。
import {loadCourses} from './actions/courseActions';
import configureStore from './store/configureStore';
const store = configureStore();
store.dispatch(loadCourses());
開發環境的configureStore文件就像這樣。
import { createStore, applyMiddleware } from 'redux';
import rootReducer from '../reducers';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from 'redux-thunk';
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(thunk, reduxImmutableStateInvariant())
);
}
另請注意,在這裏我使用的是redux-thunk中間件。除了上面的解釋之外,我還建議您也通過discussion。希望這可以幫助。快樂的編碼!
這是完整的例子嗎?連接在哪裏? – Mayday
是的,這是所有的代碼,我只移除了兩個Form標籤之間的HTML輸入元素,僅此而已。沒有連接功能 – MChan