我无法使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返回一个空对象。我在做什么错了?
答案 0 :(得分:1)
初始状态显示为已安装的组件,它是空对象{}
this.props.getTenantByID(tenantId);
此操作实际上触发了,但是在componentDidMount生命周期中没有可用数据。
尝试以这种方式登录日志
componentDidMount(){
this.props.getTenantByID(2);
}
render() {
console.log(this.props.tenantData); // 1st render => {}, 2nd render=> desired data
return (
<div/>
);
}
答案 1 :(得分:0)
使用componentDidUpdate来检查值是否已更改,
componentDidUpdate(prevProps){
if(prevProps.tenantData !== this.props.tenantData){ console.log(prevProps.tenantData, this.props.tenantData) }
}
答案 2 :(得分:0)
记住要在您的mapDispatchToProps方法中接收dispatch参数
const mapDispatchToProps = (dispatch) => {
return {
getTenantByID: (tenantID ) => {
dispatch(getTenantByID({tenantID }));
};
};
};
呼吁
this.props.getTenantByID({ tenantID: 10 })