简体   繁体   English

在迭代数组时不断获取未定义

[英]Constantly getting undefined when iterating through an array

So I'm just practising my react redux skills. 所以我只是练习我的反应减速技能。 Im a beginner. 我是初学者。 I have created an action, reducer and several components. 我创建了一个动作,减速器和几个组件。 I'm basically making a todo app. 我基本上是在做一个todo应用程序。 I am fetching the data from an API which I have successfully done but the problem is arising when I'm trying to loop through the data and have it surrounded with <li> tags. 我正在从我已成功完成的API中获取数据,但是当我尝试循环数据并将其包含在<li>标记中时,问题就出现了。 I am getting Cannot read property 'map' of undefined which i dont understand why because in the console i can clearly see the array. 我得到了Cannot read property 'map' of undefined ,我不明白为什么,因为在控制台中我可以清楚地看到数组。

Action: 行动:

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}  });
    });
}
}

Reducer: 减速器:

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;

ToDo Components: 待办事项组件:

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 Component: 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;

EDIT: 编辑:

This is what I have so far now: 这就是我现在所拥有的:

ToDoItems: 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;

ToDo Component: ToDo组件:

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;

Reducer: 减速器:

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;

Action: 行动:

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}  

});
        });
    }
}

There are now no errors yet nothing is getting displayed: 现在没有错误,但没有显示任何内容:

(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)

Afternoon, 下午,

I think the data you want is from prop.list.data not props.list within <TodoItems /> 我想你想要的数据是来自prop.list.dataprops.list<TodoItems />

In your component <TodDo /> try: 在您的组件<TodDo />尝试:

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

Then tidy up your stateless component <TodoItems /> (to cover an empty array): 然后整理你的无状态组件<TodoItems /> (以覆盖一个空数组):

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>
  );
};

Note: 注意:

Your array has an object, with this shape: 您的数组有一个对象,具有以下形状:

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

What do you want to return in your <li> ? 你想在<li>回报什么?

Update to loop through object. 更新循环对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM