我无法使mapDispatchToProps正常工作。
我导出一个CombineReducers:
export default combineReducers({
auth: AuthReducer,
tenants: TenantsReducer
});
租户减少者:
const INITIAL_STATE = {
error: false,
data: [],
tenantData: {},
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case GET_TENANTS_DATA:
return { ...state, error: false, data: action.payload };
case GET_TENANT_DATA:
return { ...state, error: false, tenantData: action.payload };
default:
return state;
}
};
然后我的动作中有getTenantByID方法
export const getTenantByID = ({ tenantID }) => {
return (dispatch) => {
const getTenant = {
FirstName: 'Jonh', LastName: 'Doe', Email: 'jonh@test.com', Phone: 'xxx-xxx-xxxx',
Unit: '101', MiddleName: '',
};
dispatch({
type: GET_TENANT_DATA,
payload: getTenant
});
};
};
最后,我尝试在组件中使用它。
import { connect } from 'react-redux';
import { getTenantByID } from '../actions';
...
componentDidMount() {
const { navigation } = this.props;
const tenantID = navigation.getParam('tenantID', '0');
this.props.getTenantByID(tenantID);
console.log(this.props);
this.state = {
tenantData: this.props.tenantData
};
}
const mapStateToProps = ({ tenants }) => {
return {
error: tenants.error,
tenantData: tenants.tenantData
};
};
const mapDispatchToProps = () => {
return {
getTenantByID
};
};
export default connect(mapStateToProps, mapDispatchToProps)(TenantDetails);
在我的componentDidMount中,console.log(this.props)为tenantData返回一个空对象。我究竟做错了什么?
初始状态显示为已安装的组件,它是空对象{}
this.props.getTenantByID(tenantId);
该操作实际上会触发,但是在componentDidMount生命周期中没有可用的数据。
尝试这样登录渲染
componentDidMount(){
this.props.getTenantByID(2);
}
render() {
console.log(this.props.tenantData); // 1st render => {}, 2nd render=> desired data
return (
<div/>
);
}
有效!我试图使用this.props.tenantData更新componentDidMount中的状态。我想我必须在render()方法中做到这一点。谢谢