简体   繁体   English

React 一直在说。map 不是 function 并且我尝试过的没有任何工作?

[英]React keeps saying .map is not a function and nothing I have tried is working?

I have a component that gets listings from and API using axios.我有一个组件,它使用 axios 从 API 获取列表。 When the home page first loads all the listings are retrieved and load fine, but when I go to say the listing detail page and back to the home page I get a 'listings.map is not a function' error, when I refresh the page I do not get the error and the listings load.当主页第一次加载时,所有列表都被检索并加载正常,但是当我 go 说列表详细信息页面并返回主页时,当我刷新页面时,我得到一个“listings.map 不是函数”错误我没有收到错误并且列表加载。

Here is the component(tried using a loading boolean but did nothing):这是组件(尝试使用加载 boolean 但什么也没做):

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getListings } from '../../actions/listings';
import { Link as RouteLink } from 'react-router-dom';
import PropTypes from 'prop-types';
//material ui
import {
  Container,
  Typography,
  Button,
  Card,
  CardActions,
  CardActionArea,
  CardContent,
  CardMedia,
  Grid,
  Link,
} from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';

const useStyles = {
  listings: {
    marginTop: '100px',
    backgroundColor: 'white',
  },
  title: {
    marginBottom: '15px',
  },
  listImg: {
    width: '250px',
    height: '250px',
  },
  card: {
    width: '275px',
    height: '300px',
  },
  media: {
    height: 140,
  },
};

class Listings extends Component {
  static propTypes = {
    listings: PropTypes.array.isRequired,
    isLoading: PropTypes.bool,
  };

  componentDidMount() {
    this.props.getListings();
  }

  render() {
    const { classes, listings } = this.props;
    return (
      <>
        <Container maxWidth='lg' className={classes.listings}>
          <Typography align='center' variant='h1' className={classes.title}>
            Recent Listings
          </Typography>
          <Grid container justify='center' spacing={8}>
            {listings &&
              listings.map((listing, index) => (
                <Grid key={index} item>
                  <Link component={RouteLink} to={`/listing/${listing._id}`}>
                    <Card className={classes.card}>
                      <CardActionArea>
                        <CardMedia
                          className={classes.media}
                          title='Contemplative Reptile'
                          image={listing.imgUrls[0]}
                        />
                        <CardContent>
                          <Typography gutterBottom variant='h6' component='h2'>
                            {listing.title}
                          </Typography>
                          <Typography
                            variant='body2'
                            color='textSecondary'
                            component='p'
                          >
                            {listing.price} /night
                          </Typography>
                        </CardContent>
                      </CardActionArea>
                      <CardActions>
                        <Button size='small' color='primary'>
                          BOOK
                        </Button>
                      </CardActions>
                    </Card>
                  </Link>
                </Grid>
              ))}
          </Grid>
        </Container>
      </>
    );
  }
}

//sets component props to the app state
const mapStateToProps = (state) => ({
  listings: state.listings.listings,
  isLoading: state.listings.isLoading,
});

//withStyles is used for material-ui styles (using class components)
export default connect(mapStateToProps, { getListings })(
  withStyles(useStyles)(Listings)
);

here is the getListings action:这是 getListings 操作:

export const getListings = () => (dispatch) => {
  axiosInstance
    .get('/listings')
    .then((res) => {
      dispatch({
        type: GET_LISTINGS,
        payload: res.data,
      });
    })
    .catch((err) => console.log(err));
};

and the reducer:和减速机:

const initialState = {
  listings: [],
  isLoading: true,
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_LISTINGS:
      return {
        ...state,
        listings: action.payload,
        isLoading: false,
      };
    case GET_LISTING:
      return {
        ...state,
        listings: action.payload,
        isLoading: false,
      };
    case CREATE_LISTING:
      return {
        ...state,
        listings: [...state.listings, action.payload],
      };
    case CLEAR_LISTINGS:
      return {
        ...state,
        listings: [],
      };
    default:
      return state;
  }
}

Just don't get how it does work, but then doesn't at times.只是不知道它是如何工作的,但有时不会。 Listings are declared as an array also in initialState.列表在 initialState 中也被声明为一个数组。

If your listings variable type is如果您的列表变量类型是

Object Object

then you have to map like this:那么你必须像这样 map :

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed

On the other hand if your variable is另一方面,如果您的变量是

Array大批

then:然后:

const numbers = [2, 4, 6, 8];
const squares = numbers.map(number => number * numbers);

console.log(squares);
// output: Array [4, 16, 36, 64]

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

相关问题 我正在读取未定义的属性 map。我已经尝试了一切但没有任何效果 - I am getting read property map of undefined.I have tried everything but nothing worked 我如何 map 反应 js 中的一个数组我试过了但是有一些问题谁能帮我 - how do i map an array in react js i have tried but there is some problem can anyone help me 使用 react-bootstrap 时出现模块未找到错误。 已尝试所有步骤 - I have module not found error while working with react-bootstrap. Have tried all the steps 为什么.map function 没有反应 - Why does .map function return nothing in react map函数在React中不起作用 - map function not working in React CSS React JS 中的模块无法正常工作,我几乎尝试了所有方法,但没有解决 - CSS Modules in React JS not working, i have tried literally everything but it didn't solved 如果要在div中找到两个类,我想删除类,但我尝试过但无法使用jQuery函数 - I want to remove class if two classes found in a div, with jQuery function I have tried but not working React Navigation 说渲染没有返回任何内容 - React Navigation saying nothing was returned from render JavaScript中的React API对象总是说未定义 - React API object in JavaScript keeps saying undefined 在React Native中,我拥有的代码没有任何渲染 - In React Native, nothing renders with the code I have
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM