我正在从API调用一个对象数组并将它们加载到状态。我从API接收有效负载,并能够将整个阵列加载到我的状态。我能够在控制台日志中看到该对象,但是当我尝试从键访问特定值时,它只返回undefined。
PullStocks: {
quote: [],
price: '',
news: [
{
datetime: '2018-05-11T09:10:00-04:00',
headline: 'Your first trade for Friday, May 11',
source: 'CNBC',
url: 'https://api.iextrading.com/1.0/stock/aapl/article/7912789597255843',
summary: 'No summary available.',
related: 'AAPL,FB,OSTK,XRX'
},
{
datetime: '2018-05-11T07:38:21-04:00',
headline: 'FANG Stocks Have Ignited A Rally - Cramer\'s Mad Money (5/10/18)',
source: 'SeekingAlpha',
url: 'https://api.iextrading.com/1.0/stock/aapl/article/6776286739960540',
summary: ' Stocks discussed on the in-depth session of Jim Cramer\'s Mad Money TV Program, Thursday , May 10. The market has been seeing negativity and selloff in the recent past. However, the non-believers have been converted to believers now. How did this happen? All it took was great earnings…',
related: 'AAPL,AMZN,BIIB,BMRN,CELG,F,FB,FCX,GILD,GRPN,GRUB,INT31168144,KSU,NASDAQ01,NLY,NSC,ONL31168,REGN,Computing and Information Technology'
}}
我可以调用state.Pullstocks.news [0]并返回控制台日志中的完整对象。我已经尝试过state.Pullstocks.news [0] .datetime,我认为它会起作用但事实并非如此。
我使用Redux作为我的状态管理,但即使返回有效负载,我也无法引用正确的密钥。
以下是我的组件的代码。
import React from "react";
import { push } from "react-router-redux";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { getNews } from "../../modules/PullStocks";
const News = props => {
const currentCompany = props.path.split("/");
if (!props.news[0]) {
props.getNews(currentCompany[2]);
}
return (
<div className="widget">
{console.log(props.news[0])}
{/* <h1>{props.news[0]}</h1>
{console.log(JSON.stringify(props.news))} */}
</div>
);
};
const mapStateToProps = state => ({
news: state.PullStocks.news,
path: state.routing.location.pathname
});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
getNews
},
dispatch
);
export default connect(mapStateToProps, mapDispatchToProps)(News);
我做错了什么?
答案 0 :(得分:0)
编辑:我可能理解这是错的。如果我没有看错,你已经在其他地方填充你的州。然后,如果没有针对特定事情执行getNews操作,则检查是否存在第一项新闻。我想知道是否没有任何第一项,控制台日志如何不会出错?
如果我是对的,你会看到这个问题,因为你的if块没有返回任何内容:
if (!props.news[0]) {
props.getNews(currentCompany[2]);
}
试试这样:
if (!props.news[0]) {
return props.getNews(currentCompany[2]);
}
由于没有返回,代码会立即跳转到下一个返回,然后再让数据尝试使用它并触发错误。
也许最好使用类组件并在componentDidMount中执行此数据提取。