【问题标题】:Constantly getting undefined when iterating through an array遍历数组时不断变得未定义
【发布时间】:2019-06-01 12:32:12
【问题描述】:

所以我只是在练习我的 react redux 技能。我是初学者。我创建了一个动作、reducer 和几个组件。我基本上是在制作一个待办事项应用程序。我正在从已成功完成的 API 中获取数据,但是当我尝试遍历数据并用<li> 标签包围时,问题就出现了。我收到Cannot read property 'map' of undefined,我不明白为什么,因为在控制台中我可以清楚地看到数组。

行动:

export function getLists(){
return function (dispatch) {
    return fetch ("https://reqres.in/api/users?page=1")
    .then( response => response.json())
    .then (json => {console.log('sdsd'); console.log(json);
        dispatch({  type: "ADD_ITEMS", payload: { json, loading: false}  });
    });
}
}

减速机:

const initialState = {
todothings: [],
loading: true
};
function rootReducer (state = initialState, action) {
    if( action.type === "ADD_ITEMS"){
        console.dir("In the ADD_ITEMS reducer" + action.payload);
        return Object.assign({}, state, {
            todothings: state.todothings.concat(action.payload.json),
            loading: action.payload.loading,
          });
    } else if ( action.type === "DELETE_ITEM") {
    } else {
        return state;
    }
} 
export default rootReducer;

待办事项组件:

import React, { Component } from 'react';
import { getLists } from '../actions/index';
import { connect } from 'react-redux';
import TodoItems from './TodoItems';

class TodosComponent extends Component {
    componentDidMount(){
        console.log('in the Todos comp -> componentDidMount()');
        this.props.getList();
    }
    render(){
        const {todothings , loading} = this.props;
        if(!loading){ 
            return(
                <div>  
                    <p>dfd</p>
                    {console.log(todothings)}
                    <TodoItems list={todothings}></TodoItems>
                </div>
            )
        } else {
            return (
                <p>Fetching from upstream.</p>
            )
        }
    }
}

function mapStateToProps(state){
    return {        
        todothings: state.todothings,
        loading: state.loading,
    }
}
function mapDispatchToProps(dispatch){
    return {
        getList: () => dispatch(getLists())
      };
}
const Todos = connect(mapStateToProps, mapDispatchToProps)(TodosComponent)
export default Todos;

TodoItem 组件:

import React from 'react';

function TodoItems (props) {
    return(
        <div>
            <ul>
            {console.log('In the todoitems')}
            {console.log(props)}

            {props.list.map( element => (
               <p>{element.data}</p>
            ))}
            </ul>
        </div>
    );
}

export default TodoItems;

编辑:

这是我目前所拥有的:

待办事项:

import React from 'react';

const TodoItems = ({ list = [] }) => {
    if (list.length === 0) return null;
    return (
      <ul>
        {list.map(item => (
          <li key={item.id} {...item}>
            <p>{item.first_name}</p>
          </li>
        ))}
      </ul>
    );
  };
export default TodoItems;

待办事项组件:

import React, { Component } from 'react';
import { getLists } from '../actions/index';
import { connect } from 'react-redux';
import TodoItems from './TodoItems';

class TodosComponent extends Component {
    componentDidMount(){
        console.log('in the Todos comp -> componentDidMount()');
        this.props.getList();
    }
    render(){
        const {todothings , loading} = this.props;
        if(!loading){ 
            return(
                <div>  
                    <p>dfd</p>
                    {console.log('in the todo comp')}
                    {console.log(todothings)}
                    <TodoItems list={todothings.data}></TodoItems>
                </div>
            )
        } else {
            return (
                <p>Fetching from upstream.</p>
            )
        }
    }
}

function mapStateToProps(state){
    return {        
        todothings: state.todothings,
        loading: state.loading,
    }
}
function mapDispatchToProps(dispatch){
    return {
        getList: () => dispatch(getLists())
      };
}
const Todos = connect(mapStateToProps, mapDispatchToProps)(TodosComponent)
export default Todos;

减速机:

const initialState = {
todothings: [],
loading: true
};

function rootReducer (state = initialState, action) {
    if( action.type === "ADD_ITEMS"){
        console.dir("In the ADD_ITEMS reducer" + action.payload);
        return Object.assign({}, state, {
            todothings: state.todothings.concat(action.payload.json.data),
            loading: action.payload.loading,
          });
    } else if ( action.type === "DELETE_ITEM") {
    } else {
        return state;
    }
} 
export default rootReducer;

行动:

export function getLists(){
return function (dispatch) {
    return fetch ("https://reqres.in/api/users?page=1")
    .then( response => response.json())
    .then (json => {console.log('sdsd'); console.log(json);
        dispatch({  type: "ADD_ITEMS", payload: { json, loading: false}  

});
        });
    }
}

现在没有错误,但什么也没有显示:

(3) [{…}, {…}, {…}]
0: {id: 1, email: "george.bluth@reqres.in", first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}
1: {id: 2, email: "janet.weaver@reqres.in", first_name: "Janet", last_name: "Weaver", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"}
2: {id: 3, email: "emma.wong@reqres.in", first_name: "Emma", last_name: "Wong", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}
length: 3
__proto__: Array(0)

【问题讨论】:

  • 您从哪个console.log 获取数据?上面的代码中有 5 个日志。
  • 来自ToDoItem组件,日志为list: Array(1) 0: data: Array(3) 0: {id: 1, email: "g.buth@reqres.in", first_name: "George", last_name: "Bluth"} 1: {id: 2, email: "janet.weaver@reqres.in", first_name: "Janet", last_name: "Weaver"} 2: {id: 3, email: "emma.wong@reqres.in", first_name: "Emma", last_name: "Wong"} length: 3 __proto__: Array(0) page: 1 per_page: 3 total: 12 total_pages: 4 __proto__: Object length: 1 __proto__: Array(0) __proto__: Object

标签: javascript reactjs redux


【解决方案1】:

下午,

我认为您想要的数据来自prop.list.data 而不是props.list 内的&lt;TodoItems /&gt;

在您的组件中&lt;TodDo /&gt; 尝试:

<TodoItems list={todothings.data}></TodoItems>

然后整理你的无状态组件&lt;TodoItems /&gt;(覆盖一个空数组):

const TodoItems = ({ list = [] }) => {
  if (list.length === 0) return null;

  return (
    <ul>
      {list.map(item => (
        <li key={item.id} {...item}>
          <ul>
            {Object.keys(item).map((data, key) => (
              <li {...{ key }}>{data}</li>
            ))}
          </ul>
        </li>
      ))}
    </ul>
  );
};

注意:

你的数组有一个对象,形状如下:

{
    id: 1,
    email: "g.buth@reqres.in",
    first_name: "George",
    last_name: "Bluth"
}

您想在&lt;li&gt; 中返回什么?

更新以循环遍历对象。

【讨论】:

  • 感谢您的回复。我现在试试。我只想连接他们所有的细节并将它们输出到每个列表中。
  • 嗯,我在检查数组是否为空的部分得到未定义的TypeError: Cannot read property 'length' of undefined
  • 您能否更新(在问题的底部)json 响应。而不是控制台副本。
  • 由于列表有一个空数组的默认参数,它不能但未定义。正如它在安装时定义的那样。您是否正确复制了副本?
  • 未定义,因为我粘贴错了。我已经正确粘贴了它,现在没有错误,但页面上没有列表输出(尽管是根据控制台输出填充的)
猜你喜欢
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 2021-10-23
  • 2021-09-06
  • 2017-02-08
  • 1970-01-01
相关资源
最近更新 更多