【问题标题】:Why can't I map through an array为什么我不能通过数组映射
【发布时间】:2020-04-07 01:57:42
【问题描述】:

我想通过数组进行映射,但出现错误: TypeError: locationAddress.map 不是函数

我是 React 和 React Hooks 的新手。我一直在尝试简化数组,但没有运气。 任何想法为什么这不起作用?

编辑:到目前为止,我尝试了答案中的所有更改,但错误仍然存​​在。 我包含了更多代码和 package.json 文件。 我尝试停用一些功能,例如 useEffect,现在错误仅在我尝试输入正在映射的输入字段时显示。

找到解决方案:

const [locationAddress, setLocationAddress] = 
useReducer(
    (state, newState) => ([{ ...state, ...newState }]),
    [{
    address: "",
    name: ""
}]);

我使用了“useReducer”并尝试在 { ...state, newState } 周围放置一些“[]”,现在它可以工作了。 感谢那些回答的人。 当您有涉及多个子值的复杂状态逻辑时,useReducer 通常比 useState 更可取。它还允许您优化触发深度更新的组件的性能,因为您可以向下传递调度而不是回调。

    import React, { Fragment, useState, useEffect, useReducer } from 'react';

import { Form, Button, Container, Row, Col } from 'react-bootstrap';
import axios from 'axios';

const FormData = () => {

    const [locationAddress, setLocationAddress] = 
    useReducer(
        (state, newState) => ([{ ...state, ...newState }]),
        [{
        address: "",
        name: ""
    }]);

    const [coordinates, setCoordinates] = useState();

    console.log(JSON.stringify(locationAddress))

    useEffect(() => {
        const fetchLocation = async () => {
            for(let i = 0; i < locationAddress.length; i++) {
                const res = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
                    params: {
                        address: locationAddress[i].address,
                        key: 'MyAPIKey'
                    }
                });
                setLocationAddress(res.data);
                setCoordinates(res.data.results[0].geometry.location);
                console.log('Coordinates: ' + JSON.stringify(coordinates));    
            }
        }
        fetchLocation();
    }, [coordinates, locationAddress]);

    const onChangeAddress = e => setLocationAddress({ ...locationAddress, [e.target.name]: e.target.value});

    const onSubmit = e => {
        e.preventDefault();
    }

    return (
        <Fragment>
            <Form onSubmit={onSubmit}>
                <ul>
                    {locationAddress && locationAddress.map(({address, name}, index) => 
                        <li key={index}>
                            <Form.Group>
                                <Form.Label htmlFor="address">Enter location</Form.Label>
                                <Form.Control type="text" name="address" id="address" value={address} onChange={onChangeAddress} />
                            </Form.Group>
                            <Form.Group>
                                <Form.Label htmlFor="name">Enter name</Form.Label>
                                <Form.Control type="text" name="name" id="name" value={name} onChange={onChangeAddress} />
                            </Form.Group>
                            <Form.Group>
                                <Button variant="secondary" type="submit">Remove friend</Button>
                            </Form.Group>
                        </li>
                    )}
                </ul>
                <Form.Group>
                    <Button variant="secondary" type="submit">Add friend</Button>
                </Form.Group>
            </Form>
        </Fragment>
    )
}

export default FormData;

Package.json

{
  "name": "map-calculator-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.19.0",
    "bootstrap": "^4.4.1",
    "prop-types": "^15.7.2",
    "react": "^16.12.0",
    "react-axios": "^2.0.3",
    "react-bootstrap": "^1.0.0-beta.16",
    "react-dom": "^16.12.0",
    "react-places-autocomplete": "^7.2.1",
    "react-scripts": "3.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

【问题讨论】:

  • locationAddress 是一个数组吗?确保它是一个数组。

标签: arrays reactjs dictionary react-hooks


【解决方案1】:

您的代码看起来不错。 用ocationAddress &amp;&amp; locationAddress.map()试试这个

               <ul>
                {locationAddress && locationAddress.map((location, index) => 
                    <li key={index}>
                        <Form.Group>
                            <Form.Label for="address">Enter location</Form.Label>
                            <Form.Control type="text" name="address" id="address" value={address} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label for="address">Enter name</Form.Label>
                            <Form.Control type="text" name="address" id="address" value={address} />
                        </Form.Group>
                        <Form.Group>
                            <Button variant="secondary" type="submit">Remove friend</Button>
                        </Form.Group>
                    </li>
                )}
            </ul>

【讨论】:

  • 感谢 Vahid,尝试了您的建议,但仍然无效...
【解决方案2】:

您的代码应该按原样运行,因为您的 locationAddress 是由 useState 钩子初始化的对象数组。

我复制了你的代码,做了一些调整:

  1. 您在.map() 期间的位置,需要解构为addressname。那么只有您可以像现在一样在FormControl 中访问它。 (或将FormControlvalues 更改为location.addresslocation.name
  2. locationAddress 中添加了一个默认数据,以确保您可以访问它以进行测试。

代码 sn-p

const { useState } = React;

function App() {
  const [locationAddress, setLocationAddress] = useState([{
    address: "US",
    name: "John Doe"
}]);

  return (
    <div className="App">
      <div>
        {
          locationAddress.map(({ address, name }) => <span>{`${address}-${name}`}</span>)
        }
      </div>
    </div>
  );
}

在使用挂钩之前,请确保您的 reactv16.8.0(或更高)。


The sandbox [link][1].


  [1]: https://codesandbox.io/s/dazzling-hellman-u4vc5

【讨论】:

  • 感谢@pritam 的回答。不幸的是,代码仍然无法正常工作,错误仍然存​​在。我想知道 React Hooks 是否有问题!?我提供了我的 package.json。我尝试删除 Bootstrap 代码,但仍然出现错误...接下来我将尝试删除 React Hooks 并使用带状态的类组件。
猜你喜欢
  • 2021-09-26
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多