【问题标题】:How to access nested state from redux如何从 redux 访问嵌套状态
【发布时间】:2021-01-29 03:34:59
【问题描述】:

我有一个简单的 React App,它有一个 redux 商店这是它的结构

AppState Structur:
rawMarketData: {
    isLoading: boolean
    results?: {
        date: string
        logs: [
            {
                sessionIndex: number
                time: string
                price: number
            },
            ...
        ]
    }
    error?: any  
}

我创建了一个测试类组件来访问状态, 当我调用操作以获取数据时,一切正常 但是当我尝试访问 logs 属性(来自上面的示例)时,我得到了 undefined 但在访问结果时它可以工作!

import React from 'react'
import { connect } from 'react-redux';

interface MarketDataLog {
    sessionIndex: number
    time: string
    price: number
}

interface RawMarketDataResults {
    date: string
    logs: MarketDataLog[]
}

interface RawMarketDataLogState {
    isLoading: boolean
    results?: RawMarketDataResults
    error?: any
}

interface AppState {
    rawMarketData: RawMarketDataLogState
}
//All of the above is the app state structure 



interface MyProps {
    rawData: RawMarketDataResults | undefined
}

class TestFile extends React.Component<MyProps> {
    render() {
        console.log('this is { results: { date, logs[] } }' + JSON.stringify(this.props.rawData)) //Works Good
        console.log('this is the { results: { logs[] } ' + JSON.stringify(this.props.rawData?.logs)) // Undefined

        return (
            <div>
                {this.props.rawData ? 'there is Data in State' : 'No data in state'}
            </div>
        );
    }
}

const mapStateToProps = (state: AppState) => {
    return { rawData: state.rawMarketData.results }
}

export default connect(mapStateToProps)(TestFile)

我做错了什么?

【问题讨论】:

  • 不应该是this.props.rawData?.results?.logs吗?
  • 不,我将结果直接用于道具,当我记录整个 rawData 时,我得到` { date: 'some date' logs: [ { sessionIndex: 0 time: 'datestring' price: '100' }, ... ]} 但 logs 本身的属性未定义
  • 我猜你不需要检查 isLoading 的值,那根本就没有理由吗?可能是因为正在加载数据而不可用? redux 开发工具是怎么说的?
  • 开发工具说一切都很好,动作被调度并且状态被填充

标签: reactjs typescript redux


【解决方案1】:

问题是 RawMarketDataResults 中缺少 []

接口 RawMarketDataLogState { isLoading:布尔值 结果?:RawMarketDataResults[] 错误?:任何 }

已修复

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 2023-03-23
    • 2020-01-26
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 2016-09-29
    • 2023-03-22
    相关资源
    最近更新 更多