单个组件中有多个Redux状态 - Typescript,React,Redux

时间:2018-02-07 08:52:46

标签: reactjs typescript redux react-router

在身份验证期间,我会返回一些需要在整个用户生命周期中携带到其他组件中的内部ID。这些值保持在authentication状态,所有其他相关组件逻辑保持在resources状态。

当我在组件中运行多个状态时,看起来身份验证状态会覆盖资源状态,尽管React状态确实具有值(确认使用了值),但值I {m} undefined React Dev Tool)。

以下是我的组件中的相关代码:

道具类型:

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;

我如何使用不同状态的示例。请在代码中查看我的评论:

    //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);
    }

我是否从根本上误解了连接如何将道具连接到Redux状态?

1 个答案:

答案 0 :(得分:4)

您期望connect()在这做什么?

export default connect(
    (state: ApplicationState) => state.resources && state.authentication,
    ResourceState.actionCreators 
)(ResourceDisplay) as typeof ResourceDisplay;

因为目前,您所说的只是state.authentication如果state.resources是&#34; truthy&#34; (它可能是)。换句话说,state.resources不会传递给您的组件。

我猜你真的想要结合两者的属性?如果是这种情况,您需要执行以下操作:

export default connect(
    (state: ApplicationState) => { ...state.resources, ...state.authentication },
    ResourceState.actionCreators 
)(ResourceDisplay) as typeof ResourceDisplay;

或使用Object.assign()或其他内容(不完全确定您希望从代码中使用哪种道具格式)。

相关问题