Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

reactjs - How to access nested state from redux

I have a simple React App that has a redux store This is its structure

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

I create a Test class component to access the state, when I call the action to get the Data everything works fine But when I try to access the logs property (from the example above) I get undefined but when accessing results it works!

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)

what am I doing wrong?

question from:https://stackoverflow.com/questions/65948440/how-to-access-nested-state-from-redux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Problem was a missing [] in RawMarketDataResults

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

Fixed


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...