这里提出了很多类似的问题,但我找不到问题的答案。
这是我的反应组件:
class MyTransitPage extends Component {
componentDidMount() {
this.props.getPassengerProfile();
}
render() {
return (
<View>
<Text>{this.props.passenger.pid}</Text>
</View>
);
}
}
const mapStateToProps = ( state ) => {
return {
passenger: state.transit.passenger
}
}
export default connect(mapStateToProps, { getPassengerProfile })(MyTransitPage)
这是我的还原器:
const initialState = {
passenger: {}
};
export default(state = initialState, action) => {
console.log("reducer ");
console.log(action.payload);
switch(action.type) {
case 'GET_PASSENGER_PROFILE':
return { ...state, passenger: action.payload};
default:
return state;
}
}
当我在还原器中执行console.log时,我可以看到有效载荷在那里:
"passenger": Object {
[20:57:55] "createdAt": "2019-02-10T13:02:40.897Z",
[20:57:55] "objectId": "YKzeH2Nh3C",
[20:57:55] "pid": "iwKHqfCQSu",
[20:57:55] "updatedAt": "2019-02-10T13:02:40.897Z",
[20:57:55] },
但是,当我尝试访问组件中的{this.props.passenger.pid}时,我会得到pid的未定义。我找不到问题所在。我在哪里弄错了?
编辑:根还原器:
export default combineReducers({
auth: AuthenticationReducer,
transit: TransitReducer
});
edit2:操作:
export const getPassengerProfile = () => {
const currentUser = Parse.User.current();
const currentUserId = currentUser._getId()
const Passenger = Parse.Object.extend('Passenger');
const query = new Parse.Query(Passenger);
query.equalTo("pid", currentUserId);
return (dispatch) => {
query.first().then(response => {
dispatch ({
type: 'GET_PASSENGER_PROFILE',
payload: response
});
});
};
}
您在componentDidmount中调用 this.props.getPassengerProfile()
,这意味着在状态从该值填充状态之前已经安装并渲染组件。我只会在您的渲染中添加一张检查,以免出现错误,然后当它到达那里时,它应该正确显示。这样:
render() {
//console.log(this.props.transit);
console.log(this.props);
return (
<View>
<Text>{this.props.passenger ? this.props.passenger.pid : ''}</Text>
</View>
);
}
我在action.payload上使用了 JSON.parse(JSON.stringify())
,这似乎已经解决了问题。