简体   繁体   English

V—array.map 不是 function --V

[英]V— array.map is not a function --V

I'm building a weather app with AccuWeather API (calling from node server), react and redux.我正在使用 AccuWeather API(从节点服务器调用)、react 和 redux 构建一个天气应用程序。

when I'm calling AutoComplete API - https://developer.accuweather.com/accuweather-locations-api/apis/get/locations/v1/cities/autocomplete ,当我调用自动完成 API - https://developer.accuweather.com/accuweather-locations-api/apis/get/locations/v1/cities/autocomplete时,

and try to map the results, I am getting this error although it is array (and if I save the response in InitialState for working with it from first render everything work fine)并尝试 map 结果,虽然它是数组,但我收到此错误(如果我将响应保存在 InitialState 中以便从第一次渲染一切正常工作)

Here is the problematic code, really can't understand why if I'm getting the result in real-time and not from default this error occurs.这是有问题的代码,真的无法理解为什么如果我是实时获得结果而不是默认情况下会发生此错误。


import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux'
import { cityAutoComplete, clearAutoComplete, getForcast } from 
'../../../store/actions/locationActions';

import { InputLabel, TextField, Select, MenuItem, FormHelperText } 
 from '@material-ui/core'

export default function Search() {

const autoComplete = useSelector(state => state.location.autoComplete)
const dispatch = useDispatch();
const [isLoading, setIsLoading] = useState(false);

const handleChange = e => {
    if (e.target.value.length > 2 && !autoComplete && !isLoading) {
        setIsLoading(true)
        dispatch(cityAutoComplete(e.target.value))
    } else if (e.target.value.length <= 2) {
        setIsLoading(false);
        dispatch(clearAutoComplete())
    }
}

const handleSubmit = e => {
    dispatch(getForcast(e.target.value))
}

if (autoComplete) {
    if (isLoading) {
        setIsLoading(false);
    }
}
return (
    <div>
     <InputLabel id="demo-simple-select-helper-label">
       <TextField label="type 3 char for running the autoComplete" 
    onChange={e=>handleChange(e)} autoComplete="newpassword" 
          variant="outlined" />
        </InputLabel>
    { !isLoading && autoComplete &&
     <Select
      labelId="demo-simple-select-helper-label"
      id="demo-simple-select-helper"
      value=''
      onChange={handleSubmit}
     >
         {autoComplete.map(city => ( <MenuItem value={city.key}> 
                {city.LocalizedName} </MenuItem>))}

    </Select>
      }
        {isLoading && <img src={require('../../../assets/loading.svg')} /> 
      }

         <FormHelperText>Search by City Name</FormHelperText>
       </div>)
  }

here is a demo response for searching "lon" -这是搜索“lon”的演示响应 -


  [{"Version":1,"Key":"328328","Type":"City","Rank":10,
  "LocalizedName":"London","Country":{"ID":"GB","LocalizedName":"United 
  Kingdom"},"AdministrativeArea":{"ID":"LND","LocalizedName":"London"}},
  {"Version":1,"Key":"57911","Type":"City","Rank":23,
  "LocalizedName":"Longyan","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea": 
  {"ID":"FJ","LocalizedName":"Fujian"}}, 
  {"Version":1,"Key":"77666","Type":"City","Rank":25,
   "LocalizedName":"Longgang District","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea": 
  {"ID":"GD","LocalizedName":"Guangdong"}}, 
  {"Version":1,"Key":"2580116","Type":"City","Rank":25,
   "LocalizedName":"Longhua District","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea": 
  {"ID":"GD","LocalizedName":"Guangdong"}}, 
  {"Version":1,"Key":"2332564","Type":"City","Rank":25,
   "LocalizedName":"Longnan","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea": 
  {"ID":"GS","LocalizedName":"Gansu"}}, 
  {"Version":1,"Key":"2332955","Type":"City","Rank":25,
   "LocalizedName":"Longhui County","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea": 
  {"ID":"HN","LocalizedName":"Hunan"}}, 
  {"Version":1,"Key":"2333548","Type":"City","Rank":25,
   "LocalizedName":"Longyang District","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea":{ 
  "ID":"YN","LocalizedName":"Yunnan"}}, 
  {"Version":1,"Key":"58368","Type":"City","Rank":33,
  "LocalizedName":"Long'an County","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea": 
  {"ID":"GX","LocalizedName":"Guangxi"}},      
{"Version":1,"Key":"58726","Type":"City","Rank":33,"LocalizedName":"Longhua 
 County","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea": 
  {"ID":"HE","LocalizedName":"Hebei"}}, 
  {"Version":1,"Key":"61050","Type":"City","Rank":33,
   "LocalizedName":"Longchang","Country": 
  {"ID":"CN","LocalizedName":"China"},"AdministrativeArea": 
  {"ID":"SC","LocalizedName":"Sichuan"}}]

my store我的商店


import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger'
import rootReducer from './reducers/rootReducer';

import { reactReduxFirebase, getFirebase } from 'react-redux-firebase';
import { reduxFirestore, getFirestore } from 'redux-firestore';
import FBConfig from '../config/FBConfig';

export const store = createStore(
  rootReducer,
  compose(
     applyMiddleware(thunk.withExtraArgument
      ({ getFirebase, getFirestore }), logger),
      reactReduxFirebase(FBConfig, {
          userProfile: 'users',
          useFirestoreForProfile: true,
          attachAuthIsReady: true
      }),
       reduxFirestore(FBConfig)
   )
);

and my action和我的行动


export const cityAutoComplete = input => {
return (dispatch, getState) => {
    fetch('http://localhost:3001/autocomplete', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ input })
        })
        .then(response => response.json())
        .then(response => {
            dispatch({ type: 'LOCATION_AUTOCOMPLETE', response })
         })

         .catch(err => dispatch({ type: 'LOCATION_ERR', err }))
   }
 }

thanks in advance!提前致谢!


** EDIT - By default, every response from a server comes in string, even if in the console.log shows its array or object. ** 编辑 - 默认情况下,来自服务器的每个响应都以字符串形式出现,即使在 console.log 中显示其数组或 object。 it is '[]' or '{}'.它是“[]”或“{}”。 JSON.parse() and all working smoothly:) JSON.parse() 一切顺利:)

Try destructuring value off of e.target .尝试从e.target解构value React creates a synthetic event in its event handlers, and sometimes the target/value won't persist when sending it to another function unless you get a reference to it. React 在其事件处理程序中创建一个合成事件,有时目标/值在将其发送到另一个 function 时不会持续存在,除非您获得对它的引用。

const handleSubmit = e => {
  const { value } = e.target;
  dispatch(getForcast(value));
}

(Try this for both handleSubmit and handleChange) (对 handleSubmit 和 handleChange 都试试这个)

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

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