react+redux+redux-thunk项目获取数据,读不到数组内字段

最近刚学了react,准备用react+redux+redux-thunk做一个移动端的文章阅读项目。
没想到一开始就出现了棘手的问题,请各位大神给分析一下。

问题描述

使用rdeux+redux-thunk做数据管理
采用axios获取文章列表数据
state中已经获取到数据,但是在页面刷新时会报出×
TypeError: Cannot read property 'title' of undefined

问题出现的环境背景及自己尝试过哪些方法

尝试用 {this.state.articleListValue[1].title}取值插入到list中
通过在页面中打印state数据,正常打印出数据,可是组件中还是读不到title字段

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)
组件代码

import React, { Component } from 'react';
import 'antd-mobile/dist/antd-mobile.css'; 
import { List,Button } from 'antd-mobile';
import store from './store/index'
import { getArticleList }from './store/actionCreators'
const Item = List.Item;
const Brief = Item.Brief;
class ArticleList extends Component {
    constructor(props){
        super(props)
        this.state = store.getState();
        
    }
    render() { 
        return ( 
            <div>
                  <List renderHeader={'Align Vertical Center'} className="my-list">
                  <Item multipleLine extra="额外内容">
                    {this.state.articleListValue[1].title}
                    <Brief>{"副标题"}</Brief>
                  </Item>
                </List>
              
            <Button onClick = {this.handleBtn.bind(this)} >222</Button>
           </div>
         );
    }
   
    componentDidMount() {
      const action = getArticleList();
      store.dispatch(action); 
      
  }
     
    handleBtn(){
      console.log(this.state.articleListValue[1].title)
    }
        
}
 
export default ArticleList;

actionCreators'代码

import axios from 'axios'

export const getArticleList = () => {
    return (dispatch) => {
        axios.get('https://www.jianshu.com/asimov/trending/now')
            .then((res) => {
                const data = res.data
                const action = {
                    type: 'getArticleListValue',
                    data: data
                }
                dispatch(action)
            })
    }
}

reducer代码

const defaultState = {
    articleListValue:[]
}

export default (state = defaultState,action)=>{
    if(action.type==='getArticleListValue'){
        const newState = state
        const articleList = new Array()
        for(var i = 0;i<action.data.length;i++){
          articleList[i] = action.data[i].object.data
      }
      newState.articleListValue = articleList
      return newState;
    }
    return state;
}

state数据结构
图片描述

请给位大神给看一下,有什么优化的方法

阅读 1.8k
1 个回答

因为在第一次渲染的时候this.state.articleListValue[1]是不存在的,所以在初次渲染的时候就报错了。可以改成

this.state.articleListValue[1] && this.state.articleListValue[1].title

或者用optional chaining的语法:

this.state.articleListValue[1]?.title
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题