gpt4 book ai didi

javascript - ReactJS 访问嵌套对象

转载 作者:行者123 更新时间:2023-11-30 20:31:36 26 4
gpt4 key购买 nike

我正在调用 https://api.coinmarketcap.com/v2/global/ , 要显示每个属性,我可以访问 active_cryptocurrenciesactive_markets 但不能访问 total_market_captotal_volume_24h。它说它们是 undefined

import React, { Component } from "react";
import { render } from "react-dom";
import PropTypes from "prop-types";
import styled from "styled-components";
import { ScaleLoader } from "halogenium";

import styleConstants from "../misc/style_constants.js";

import { connect } from "react-redux";

import { fetchMarketOverviewData } from "../actions/api";

const Wrapper = styled.section`
color: ${styleConstants.get("Light")};
margin: 20px 0;
`;

const Table = styled.table`
width: 100%;
`;

const TableData = styled.td`
&:nth-child(even) {
text-align: right;
}
padding: 5px;
border-bottom: #234558 solid 0.1px;
`;

const formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 0
});

export class Overview extends Component {
state = {
isLoading: true
};

static propTypes = {
overview: PropTypes.object
};

static defaultProps = {
overview: {}
};

componentDidMount() {
this.props.fetchOverviewData;
}

static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.overview === undefined) return null;
console.log("next Props", nextProps);
return {
isLoading: false
};
}

render() {
if (this.state.isLoading) {
return (
<ScaleLoader
color={styleConstants.get("Light")}
size="16px"
margin="4px"
/>
);
} else {
let {
active_cryptocurrencies,
active_markets,
quotes
} = this.props.overview;
console.log("Overview Render() : ", this.props.overview);
return (
<Wrapper>
<Table>
<tbody>
<tr>
<TableData>Total Market Cap</TableData>
<TableData>{formatter.format()}</TableData>
</tr>
<tr>
<TableData>Total 24 Volume</TableData>
<TableData>{formatter.format(4)}</TableData>
</tr>
<tr>
<TableData>Active Markets</TableData>
<TableData>{active_markets}</TableData>
</tr>
<tr>
<TableData>Active Currencies</TableData>
<TableData>{active_cryptocurrencies}</TableData>
</tr>
</tbody>
</Table>
</Wrapper>
);
}
}
}

const mapStateToProps = state => {
const { data } = state.api.marketOverviewData;
return {
overview: data
};
};

const mapDispatchToProps = dispatch => ({
fetch: dispatch(fetchMarketOverviewData())
});

export default connect(mapStateToProps, mapDispatchToProps)(Overview);

这是 codingsandbox任何见解将不胜感激,谢谢。

最佳答案

您需要调用 this.props.fetch() 而不是 this.props.fetchOverviewData;

componentDidMount() {
this.props.fetch();
}

额外的思考:使用 componentDidMount,将有一个初始渲染,并且由于获取尚未完成,因此数据将是未定义的。您要么需要某种机制来停止渲染,直到您获得数据(即加载程序),或者为您需要访问的数据设置默认值,以便它可以使用它直到获取完成

关于javascript - ReactJS 访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50284640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com