【问题标题】:Multiple Redux states in a single component - Typescript, React, Redux单个组件中的多个 Redux 状态 - Typescript、React、Redux
【发布时间】:2018-07-17 11:42:56
【问题描述】:

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

当我在组件中使用多个状态运行时,身份验证状态似乎以某种方式覆盖了资源状态,使我得到的值 undefined 尽管 React 状态肯定具有这些值(使用 React 开发工具确认)。

这是我的组件中的相关代码:

道具类型:

type ResourceProps =
    ResourceState.ResourceState
    & AuthState.AuthState
    & typeof ResourceState.actionCreators
    & RouteComponentProps<{ }>;

Redux 连接:

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

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

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

我只是从根本上误解了 connect 是如何将 props 连接到 Redux 状态的吗?

【问题讨论】:

    标签: reactjs typescript redux react-router


    【解决方案1】:

    您希望connect() 在这里做什么?

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

    因为目前,您所说的是仅在 state.resources 是“真实的”(可能是)时才返回 state.authentication。换句话说,state.resources 不会被传递给你的组件。

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

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

    或使用Object.assign() 或其他东西(不完全确定您希望从代码中获得什么道具格式)。

    【讨论】:

    • 这绝对是我想要达到的目标,我当时很累,觉得犯了这样的错误真的很愚蠢。我在声称该类不提供匹配项的 Typescript 编译器方面遇到问题,但这在某种程度上回答了我的问题并解决了问题。谢谢。
    • 谢谢!这也引起了我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2021-01-24
    • 2018-08-05
    • 2022-06-12
    • 2019-04-27
    • 2019-02-27
    相关资源
    最近更新 更多