谁能看出我的笨蛋有什么问题? 从不调用内部代码,但调用外部代码。 这是一个示例 thunk:
export function selectCustomer(customerId) {
console.log("This appears in the console fine");
return (dispatch, getState) => {
console.log("This doesn't.. why don't you run..?");
dispatch(loadCustomerToEdit(customerId));
}
};
这就是我将其连接到组件事件的方式:
import React, { Component, PropTypes } from 'react';
import CustomerEditForm from './CustomerEditForm.jsx';
import { editCustomer, selectCustomer, selectNewCustomer, saveCustomer } from '../redux/action_creators.jsx';
export const CustomerContainer = React.createClass({
componentWillMount() {
const customerId = FlowRouter.getParam('_id');
if (customerId) {
this.sub = Meteor.subscribe('CustomerCompany.get', customerId, this.setCustomerInState);
} else {
this.props.selectNewCustomer();
}
},
setCustomerInState() {
console.log("setCustomerInState");
this.props.selectCustomer(FlowRouter.getParam('_id'));
},
// Snip
render() {
console.log("CustomerContainer.render()", this.props);
if (this.sub && !this.sub.ready) {
return (<h1>Loading</h1>);
}
return (
<CustomerEditForm
customer = {this.props.customer}
onChange = {this.props.onChange}
onSave = {this.props.onSave}
errors = {this.props.customer.errors}
isValid = {this.props.customer.isValid}
salesRegionOptions={SalesRegions.find().fetch()}
/>
);
}
});
CustomerContainer.propTypes = {
customer: PropTypes.object,
onSave: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
selectCustomer: PropTypes.func.isRequired,
selectNewCustomer: PropTypes.func.isRequired
};
function mapStateToProps(state) {
console.log("CustomerContainer.mapStateToProps", state)
return {
customer: state.userInterface.customerBeingEdited
};
}
function mapDispatchToProps(dispatch) {
//console.log("CustomerContainer.mapDispatchToProps", Actions.customerSave)
return {
onSave: saveCustomer,
onChange: editCustomer,
selectCustomer,
selectNewCustomer
};
}
export default connect(mapStateToProps, mapDispatchToProps
)(CustomerContainer);
这是我的商店设置:
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import rootReducer from './reducers.jsx';
import thunk from 'redux-thunk';
const middleware = [ thunk ]
const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore)
const store = createStoreWithMiddleware(rootReducer)
export default store;
毫无疑问,您会认识到很多代码,因为它改编自 redux 文档中的优秀示例。
调用了selectCustomer
函数,因此mapDispatchToProps
似乎已将selectCustomer
函数连接到组件,只是没有调用selectCustomer
返回的方法。
问题是你的mapDispatchToProps
函数。 如果您向它传递一个函数,React-Redux 不会自动包装您的动作创建者,只有当您向它传递一个对象时!(或者如果您使用 bindActionCreators
手动绑定它们)
尝试将connect
调用更改为此调用,它应该可以工作:
connect(mapStateToProps, {
onSave: saveCustomer,
onChange: editCustomer,
selectCustomer,
selectNewCustomer
})(YourComponent);