【问题标题】:Redux + Thunk + Axios + Consume external API: "Uncaught TypeError: Cannot read property '1' of undefined"Redux + Thunk + Axios + 使用外部 API:“未捕获的类型错误:无法读取未定义的属性 '1'”
【发布时间】:2017-09-27 14:12:15
【问题描述】:

我刚开始使用 Redux 和外部 API。为了学习,我想使用来自 NASA (https://api.nasa.gov/) 的 API。我不知道我做错了什么。我无法在屏幕上渲染任何东西。我在控制台中收到“Uncaught TypeError: Cannot read property '1' of undefined”。

我已经阅读了stackoverflow中的几个问答...但是我没有发现我的代码中的问题出在哪里。

我真的很感激任何意见。我需要一个线索...在此先感谢。

容器

import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux'
import { showTutusers } from '../actions/index';
import { bindActionCreators } from "redux";

class TutuserListContainer extends Component {

  componentWillMount() {
    this.props.showTutusers()
  }

  render() {
    return (

      <div>     
           <h3> { this.props.tutusers.photos[0].id}</h3><br />
           <h3> { this.props.tutusers.photos[1].id}</h3><br />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    tutusers: state.tutuser.tutusers
  }
}

export default connect(mapStateToProps, { showTutusers })(TutuserListContainer)

减速器 - 索引

import {combineReducers} from 'redux';
import { showTutusers } from './tutusers'


const allReducers = combineReducers({
    tutuser: showTutusers, 
});

export default allReducers

减速器

import { FETCH_TUTUSERS_START, FETCH_TUTUSERS_ERROR, RECEIVED_TUTUSERS } from '../actions/action-types';

const initialState = {
    fetching: false,
    fetched: false,
    tutusers: [],
    error: null
}

export function showTutusers(state = initialState, action) {
    switch (action.type) {
        case FETCH_TUTUSERS_START: {
            return {...state, fetching: true}
            break; 
        }
        case FETCH_TUTUSERS_ERROR: {
            return {...state, fetching: false, error: action.payload}
            break; 
        }
        case RECEIVED_TUTUSERS: {
            return {...state, fetching: false, fetched: true, tutusers: action.payload}
            break; 
        }
    }
    return state

}

动作类型

    export const SHOW_TUTUSERS = 'SHOW_TUTUSERS';
    export const FETCH_TUTUSERS_START = 'FETCH_TUTUSERS_START';
    export const FETCH_TUTUSERS_ERROR = 'FETCH_TUTUSERS_ERROR';
    export const  RECEIVED_TUTUSERS = ' RECEIVED_TUTUSERS';

操作 - 索引

import * as types from '../actions/action-types';
import axios from 'axios';
import store from '../stores/store';

export function showTutusers() {
    return (dispatch, getState) => {
        store.dispatch( { type: types.FETCH_TUTUSERS_START} ) 
        axios.get('https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=_____MY_KEY____')
            .then((response) => {
                store.dispatch( { type: types.RECEIVED_TUTUSERS, payload: response.data } ) 
               // console.log(">>> response.data", response.data)             
            }) 
            .catch((err) => {
                dispatch({type: "FETCH_TUTUSERS_ERROR", payload: err})
            })
    }

} 

商店

import { createStore, applyMiddleware, compose } from 'redux';
import allReducers from '../reducers';
import thunk from 'redux-thunk';
// import promise from 'redux-promise';
import createLogger from 'redux-logger';
import promise from 'redux-promise-middleware';

const middleware = applyMiddleware(thunk, promise(), createLogger());

const store = createStore(
    allReducers,
    compose(middleware, window.devToolsExtension ? window.devToolsExtension() : f => f)
);

export default store;

【问题讨论】:

    标签: api react-redux axios redux-thunk


    【解决方案1】:

    您需要等到收到回复,然后才尝试访问照片,这样的事情应该会有所帮助:

     <div> 
       {this.props.tutusers.fetched && <div>    
           <h3> { this.props.tutusers.photos[0].id}</h3><br />
           <h3> { this.props.tutusers.photos[1].id}</h3><br />
      </div>}
    </div>
    

    您还需要传递有关请求的所有数据:

    function mapStateToProps(state) {
      return {
        tutusers: state.tutuser
      }
    }
    

    【讨论】:

    • 感谢您的快速回复@Shota。我包括了你的建议。现在没有出现错误,但屏幕上没有呈现任何内容。有什么线索吗?顺便说一句,我的容器里已经有了。
    • 你能console.log this.props.tutusers 包含什么吗?
    • 嗨@Shota。如果我控制台日志最初是一个空数组,后来:Object {photos: Array(856)}如果我点击它:photos : Array(856) 如果我点击它:[0 … 99] 如果我点击它,你会看到对象的数据。基本上你可以在我之前的截图中看到。
    • 如果我控制台日志 this.props.tutusers.photos 最初我得到 undefined 几秒钟后我得到: [Object,对象,对象...]。但是,如果我控制台日志 this.props.tutusers.photos[1] 我得到 Uncaught TypeError: Cannot read property '1' of undefined,几秒钟后没有任何变化.
    【解决方案2】:

    我在这个 stackoverflow 问题中得到了解决方案:react redux-thunk component doesn't render this.props

    基本上我只需要一个 if else 语句:

    render() {
            var component;
            if (this.props.tutusers) {
                component = this.functionToRenderTutusers()
            } else {
                component = <h3>Loading...</h3>;
            }
            return (            
                <div>
                    {component}
                </div>
            );
        };
    

     functionToRenderTutusers() {
        return this.props.tutusers.photos.map((tutuser) => {
          return (
             <div>{tutuser.id}</div>
          )
        })
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      相关资源
      最近更新 更多