TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) - 为什么?这是什么意思?如何解决?

时间:2021-03-21 14:00:42

标签: javascript reactjs react-hooks typeerror

我试图在 search.js 和 result.js 组件之间使用 react useContext 钩子,但不知何故它不起作用。

我想将数据从一个组件发送到另一个组件。使用 props 有点复杂,所以我决定使用 context api。我也增加了价值,但为什么它不是可迭代的?它正在到达结果组件,但是 contextApi 的破坏行在这里造成了一个大问题。

我得到的错误是 TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))

search.js 代码 ->

import React, { createContext, useState } from 'react';
import { useHistory, useParams } from 'react-router';
import './Search.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Link } from 'react-router-dom';
import vehicleData from '../Home/vehicleData.json';

export const PlaceContext = createContext();

const Search = () => {
    const [searchPlace, setSearchPlace] = useState({
    from: '',
    to: ''
})

const [route, setRoute] = useState({
    from: '',
    to: ''
})

const {type} = useParams();
let ride;

vehicleData.map(vehicle => {
    
    if(vehicle.Name === type) {
        ride = vehicle.Name;
    }
})


const handleBlur = (event => {
    const newSearchPlace = {...searchPlace}
    newSearchPlace[event.target.name] = event.target.value;
    setSearchPlace(newSearchPlace);
})

const history = useHistory();

const resultPage = rideOption => {
    const url = `/result/${rideOption}`;
    history.push(url);
    console.log("pacche");
  }

const handleClick = (event) => {
    if (searchPlace.from && searchPlace.to) {
        setRoute(searchPlace);
        console.log(searchPlace, " && ", route);
    }
}

console.log(searchPlace);

return (
    <PlaceContext.Provider value={[searchPlace, setSearchPlace]}>
        <div className="d-flex flex-column searchField">
            <div className="inputArea">
                <h4>From</h4>
                <input onBlur={handleBlur} name="from" id="fromField" type="text" placeholder="Type Your Starting Point" />
            </div>
            <div className="inputArea">
                <h4>To</h4>
                <input onBlur={handleBlur} name="to" id="toField" type="text" placeholder="Type Your Destination Point" />
            </div>
            <button onMouseEnter={handleClick} onClick={() => resultPage(ride)} className="checkBtn btn btn-success btn-outline-info btn-lg m-3">Check</button>
        </div>
    </PlaceContext.Provider>
    );
};

export default Search;

和 result.js 代码 ->

import { useParams } from 'react-router';
import 'bootstrap/dist/css/bootstrap.min.css';
import './Result.css';
import vehicleData from '../Home/vehicleData.json';
import { PlaceContext } from '../Search/Search';


const Result = () => {

    const [searchPlace, setSearchPlace] = useContext(PlaceContext);

    console.log(searchPlace);

    const {ride} = useParams();
    let transportOption = ride;

    let transportName, transportImg;

    vehicleData.map(vehicle => {
        if(vehicle.Name === transportOption) {
            transportName = vehicle.Name;
            transportImg = vehicle.imgUrl;
        }
    })
    
    return (
        <div className="d-flex justify-content-between showComponent">
            <div className="placeAndPrice">
                <div className="placeName">
                    <p>From : {}</p>
                    <p>To   : {}</p>
                </div>
                <div className="d-flex justify-content-around pricePart">
                    <img src={transportImg}/>
                    <div className="d-flex flex-column priceBox">
                        <p>{transportName}</p>
                        <p>131 Taka</p>
                    </div>
                </div>
            </div>
            <div className="mapBox">
            <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d7304.049644099905!2d90.3781836249269!3d23.746494238365205!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3755b8b0e848958f%3A0xd56e2e3180c6a3ce!2sKalabagan%2C%20Dhaka%201205!5e0!3m2!1sen!2sbd!4v1616325753856!5m2!1sen!2sbd" loading="lazy"></iframe>
            </div>
        </div>
    );
};

export default Result;```



So what is the error and how to solve it?

2 个答案:

答案 0 :(得分:0)

当您尝试遍历不可迭代实体时会出现错误。在您的情况下,vehicleData 似乎是该对象(不可迭代)而不是数组(可迭代)。

EDIT - 我认为上述内容会给出 .map is not a function。 我注意到的一件事是,您实际上并没有在 {children} 中使用任何 PlaceContext.Provider 道具,所以您实际上如何能够执行以下操作:-

<Search>
<Result/>
</Search>

理想情况下,您的 PlaceContext.Provider 位应具有以下实现类型:-

return (
    <PlaceContext.Provider value={[searchPlace, setSearchPlace]}>
        /* {Your own divs and bla bla} */
        {children} 
       /* the above will come from Search prop */
    </PlaceContext.Provider>
    );
};

如果您没有太多的 Result 需要考虑,您也可以直接使用 children 代替 children

请检查您的实施是否符合此处描述的内容 - https://reactjs.org/docs/context.html#contextprovider

答案 1 :(得分:0)

当我看到您的代码时,您正在从 json 文件 (vehicleData.json) 导入 vehicleData 您可能想要检查 vehicleData 是否由 console.log(vehicleData) 正确导入。如果数据按预期导入,请检查 vehicleData 是否为数组类型。如果没有,则不能使用地图功能。如果您的数据是对象类型,那么您可以使用以下内容:

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