问题
During authentication I return some internal ids that need to be carried into other components throughout the users life cycle. These values are kept in the authentication state, and all other relevant component logic is kept in the resources state.
When I am running with multiple states in the component, it appears the authentication state overwrites the resources state in someway making the values I'm getting undefined despite the React state definitely having the values (Confirmed using the React Dev Tool).
Here is the relevant code from my component:
The props type:
type ResourceProps =
ResourceState.ResourceState
& AuthState.AuthState
& typeof ResourceState.actionCreators
& RouteComponentProps<{ }>;
Redux connect:
export default connect(
(state: ApplicationState) => state.resources && state.authentication,
ResourceState.actionCreators
)(ResourceDisplay) as typeof ResourceDisplay;
Example of how I'm using the different states. Please see my comments in the code:
//customerInfo comes from authentication state.
if (this.props.customerInfo.subscriptions.length == 0) {
console.log('empty subs list');
}
else {
this.props.customerInfo.subscriptions.forEach(function (subscription) {
// retrieveResources is an action being called from resources. This action populates the resources state.
this.props.retrieveResources(subscription);
});
// This is the resources state that is definitely populated but returning `undefined` in the code.
console.log(this.props.resources);
}
Am I just fundamentally misunderstanding how connect actually connects props to the Redux state?
回答1:
What are you expecting connect() to do here?
export default connect(
(state: ApplicationState) => state.resources && state.authentication,
ResourceState.actionCreators
)(ResourceDisplay) as typeof ResourceDisplay;
Because at the moment, what you're saying is to only return state.authentication if state.resources is "truthy" (which it probably is). In other words, state.resources won't be passed to your component.
I'm guessing you actually want to combine properties from both? If that is the case you need to do something like:
export default connect(
(state: ApplicationState) => { ...state.resources, ...state.authentication },
ResourceState.actionCreators
)(ResourceDisplay) as typeof ResourceDisplay;
Or use Object.assign() or something else (not entirely sure what props format you expect from your code).
来源:https://stackoverflow.com/questions/48659484/multiple-redux-states-in-a-single-component-typescript-react-redux