Javascript 映射返回此同一对象的2倍,但应仅返回1
我正在尝试从API获取数据,当我尝试使用map array获取感兴趣的数据时,我的程序会下载,第一次搜索同一对象2次,第二次搜索6次。Javascript 映射返回此同一对象的2倍,但应仅返回1,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我正在尝试从API获取数据,当我尝试使用map array获取感兴趣的数据时,我的程序会下载,第一次搜索同一对象2次,第二次搜索6次。我不知道为什么。我检查了useEffect,该函数只在预期时间提取一次。 问题是当我想显示5天,我想显示每一天每小时的预测 我的期望:映射5天内返回1个数组 我现在收到的信息:map在5天内返回2个相同的数组 以下是代码: App.js import React,{useState}来自“React”; 从“./Form”导入表单; 从“./Weather”导入天
我不知道为什么。我检查了useEffect,该函数只在预期时间提取一次。
问题是当我想显示5天,我想显示每一天每小时的预测
我的期望:映射5天内返回1个数组
我现在收到的信息:map在5天内返回2个相同的数组
以下是代码: App.js
import React,{useState}来自“React”;
从“./Form”导入表单;
从“./Weather”导入天气;
从“../services/useSyncFetch”导入useSyncFetch;
常量应用=()=>{
常量url=”http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json";
const key=“**********************”;
const[idCity,setIdCity]=useState();
const data=useSyncFetch(url+“/sitelist?”+键);
返回(
);
}
导出默认应用程序;
Form.js
import React,{useState}来自“React”;
常量形式=({setIdCity,data})=>{
const[cityName,setCityName]=useState(“”);
常数findId=(e)=>{
const cities=data.Locations.Location;
cities.forEach(city=>{
const userInput=cityName.toLowerCase();
const dataCitiesName=city.name.toLowerCase();
如果(userInput==dataCitiesName){
console.log(city.name,city.id)
返回setIdCity(city.id)
}
});
}
常量handleClick=(e)=>{
e、 预防默认值();
findId();
}
常量handleChange=e=>{
setCityName(e.target.value)
}
返回(
地点:
检查
);
}
导出默认表单;
Weather.js
import React,{useState,useffect}来自“React”;
从“./天”导入天;
常量天气=({idCity,url,apiKey})=>{
const[location,setLocation]=useState({});
const[isLoading,setIsLoading]=useState(true);
useffect(()=>{
获取(url+`/${idCity}?res=3hourly&`+apiKey)
.then(response=>response.json())
。然后(数据=>{
setLocation(data.SiteRep.DV.Location);
setIsLoading(错误)
})
},[apiKey,idCity,url])
如果(孤岛加载){
返回(
请填写位置并单击“检查”
)
}如果(!isLoading),则为else{
const days=地点。期间
返回(
{location.name}
{location.country}
{days.map(元素=>(
))}
{console.log(天,“天”)}
)
}
}
////重新加载程序的错误应为天。映射(元素=>{
//element.Rep.map(日期=>)
// })
导出默认天气;
白天
从“React”导入React;
从“./Hours”导入小时数
常数日=({天,日期,小时预测})=>{
const dayDate=date.slice(0,10);
const forecast hour=hourlyForecast.map(元素=>(
))
返回(
{dayDate}
{预测小时数}
{console.log(hourlyForecast,“Hours”)}
);
}
出口违约日;
小时数
import React,{useState}来自“React”;
常数天气类型=[
{id:0,天气:“晴朗的夜晚”},
{id:1,天气:“晴朗的一天”},
{id:2,天气:“部分多云(夜间)”},
{id:3,天气:“部分阴天”},
{id:4,天气:“未使用”},
{id:5,天气:“薄雾”},
{id:6,天气:“雾”},
{id:7,天气:“多云”},
{id:8,天气:“阴天”},
{id:9,天气:“小雨阵雨(夜间)”},
{id:10,天气:“小雨阵雨(白天)”},
{id:11,天气:“毛毛雨”},
{id:12,天气:“小雨”},
{id:13,天气:“大雨阵雨(夜间)”},
{id:14,天气:“大雨阵雨(白天)”},
{id:15,天气:“大雨”},
{id:16,天气:“雨夹雪阵雨(夜间)”},
{id:17,天气:“冰雹雨(白天)”},
{id:18,天气:“雨夹雪”},
{id:19,天气:“冰雹雨(夜间)”},
{id:20,天气:“冰雹雨(天)”},
{id:21,天气:“冰雹”},
{id:22,天气:“小雪阵雨(夜间)”},
{id:23,天气:“小雪阵雨(白天)},
{id:24,天气:“小雪”},
{id:25,天气:“大雪阵雨(夜间)”},
{id:26,天气:“大雪阵雨(白天)”},
{id:27,天气:“大雪”},
{id:28,天气:“雷雨(夜间)”},
{id:29,天气:“雷雨(白天)”},
{id:30,天气:“打雷”},
]
常数小时=({Hours})=>{
让温度;
让我们感受一下温度;
让风吹;
让天气类型;
让能见度;
让紫外线;
让时间;
让我跳;
让天气预报文本;
const hour=hours.map(元素=>{
开关(元件V){
案例“VP”:
能见度=“非常差-小于1公里”
打破
案例“PO”:
能见度=“较差-1-4公里之间”
打破
案例“MO”:
能见度=“中等-在4-10公里之间”
打破
案例“GO”:
能见度=“良好-在10-20公里之间”
打破
案例“VG”:
能见度=“非常好-在20-40公里之间”
打破
案例“EX”:
能见度=“卓越-超过40公里”
打破
违约:
可见性=“未知”
打破
}
if(element.U 2&&element.U<5){
UV=“适度暴露。中午找阴凉处,遮盖并涂防晒霜”
}else if(元素)。
import React, { useState} from 'react';
import Form from './Form';
import Weather from './Weather';
import useSyncFetch from '../services/useSyncFetch';
const App = () => {
const url = "http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json";
const key = "*********************";
const [idCity, setIdCity] = useState();
const data = useSyncFetch(url + "/sitelist?" + key);
return (
<div className="wrapper">
<Form
setIdCity={setIdCity}
data={data}
/>
<Weather
idCity={idCity}
url={url}
apiKey={key}
/>
</div>
);
}
export default App;
import React, { useState } from 'react';
const Form = ({setIdCity, data}) => {
const [cityName, setCityName] = useState('');
const findId = (e) =>{
const cities = data.Locations.Location;
cities.forEach(city => {
const userInput = cityName.toLowerCase();
const dataCitiesName = city.name.toLowerCase();
if(userInput === dataCitiesName){
console.log(city.name, city.id)
return setIdCity(city.id)
}
});
}
const handleClick = (e) => {
e.preventDefault();
findId();
}
const handleChange = e => {
setCityName(e.target.value)
}
return (
<form>
<label htmlFor="location">Location: </label>
<input
onChange={handleChange}
type="text"
name="location"
id="location" />
<button onClick={handleClick}>Check</button>
</form>
);
}
export default Form;
import React, { useState, useEffect } from 'react';
import Day from './Day';
const Weather = ({ idCity, url, apiKey }) => {
const [location, setLocation] = useState({});
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch(url + `/${idCity}?res=3hourly&` + apiKey)
.then(response => response.json())
.then(data => {
setLocation(data.SiteRep.DV.Location);
setIsLoading(false)
})
}, [apiKey, idCity, url])
if (isLoading) {
return (
<h2>Please write location and click check</h2>
)
} else if(!isLoading){
const days = location.Period
return (
<div>
<p>{location.name}</p>
<p>{location.country}</p>
{days.map(element => (
<Day
key={element.value}
days={days}
hourlyForecast={element.Rep}
date={element.value}
/>
))}
{console.log(days, "Days")}
</div>
)
}
}
// //Bug is with rerender should be days.map(element => {
// element.Rep.map(day => )
// })
export default Weather;
import React from 'react';
import Hours from './Hours'
const Day = ({ days, date, hourlyForecast }) => {
const dayDate = date.slice(0, 10);
const forecastForHour = hourlyForecast.map(element => (
<Hours
key={element.$}
hours={hourlyForecast}
/>
))
return (
<div>
<p>{dayDate}</p>
{forecastForHour}
{console.log(hourlyForecast, "Hours")}
</div>
);
}
export default Day;
import React, { useState } from 'react';
const weatherTypes = [
{ id: 0, weather: "Clear night" },
{ id: 1, weather: "Sunny day" },
{ id: 2, weather: "Partly cloudy (night)" },
{ id: 3, weather: "Partly cloudy (day)" },
{ id: 4, weather: "Not used" },
{ id: 5, weather: "Mist" },
{ id: 6, weather: "Fog" },
{ id: 7, weather: "Cloudy" },
{ id: 8, weather: "Overcast" },
{ id: 9, weather: "Light rain shower (night)" },
{ id: 10, weather: "Light rain shower (day)" },
{ id: 11, weather: "Drizzle" },
{ id: 12, weather: "Light rain" },
{ id: 13, weather: "Heavy rain shower (night)" },
{ id: 14, weather: "Heavy rain shower (day)" },
{ id: 15, weather: "Heavy rain" },
{ id: 16, weather: "Sleet shower (night)" },
{ id: 17, weather: "Sleet shower (day)" },
{ id: 18, weather: "Sleet" },
{ id: 19, weather: "Hail shower (night)" },
{ id: 20, weather: "Hail shower (day)" },
{ id: 21, weather: "Hail" },
{ id: 22, weather: "Light snow shower (night)" },
{ id: 23, weather: "Light snow shower (day)" },
{ id: 24, weather: "Light snow" },
{ id: 25, weather: "Heavy snow shower (night)" },
{ id: 26, weather: "Heavy snow shower (day)" },
{ id: 27, weather: "Heavy snow" },
{ id: 28, weather: "Thunder shower (night)" },
{ id: 29, weather: "Thunder shower (day)" },
{ id: 30, weather: "Thunder" },
]
const Hours = ({ hours }) => {
let temperature;
let feelLikeTemperature;
let wind;
let weatherType;
let visibility;
let UV;
let time;
let pop;
let weatherText;
const hour = hours.map(element => {
switch (element.V) {
case "VP":
visibility = "Very poor - less than 1 km "
break;
case "PO":
visibility = "Poor - Between 1-4 km "
break;
case "MO":
visibility = "Moderate - Between 4-10 km"
break;
case "GO":
visibility = "Good - Between 10-20 km"
break;
case "VG":
visibility = "Very good - Between 20-40 km"
break;
case "EX":
visibility = "Excellent - More than 40 km"
break;
default:
visibility = "Unknown"
break;
}
if (element.U <= 2) {
UV = "Low exposure. No protection required. You can safely stay outside"
} else if (element.U > 2 && element.U < 5) {
UV = "Moderate exposure. Seek shade during midday hours, cover up and wear sunscreen"
} else if (element.U === 6 || element.U === 7) {
UV = "High exposure. Seek shade during midday hours, cover up and wear sunscreen"
} else if (element.U >= 8 && element.U < 11) {
UV = "Very high. Avoid being outside during midday hours. Shirt, sunscreen and hat are essential"
} else {
UV = "Extreme. Avoid being outside during midday hours. Shirt, sunscreen and hat essential."
}
weatherType = element.W;
temperature = element.T;
time = element.$/60;
feelLikeTemperature = element.F;
wind = element.S;
pop = element.Pp;
})
const checkWeatherType = weatherTypes.map(type=>{
// console.log(weatherType)
if(weatherType === type.id) return weatherText = type.weather;
else return weatherText=type.weather;
})
return (
<div>
<p>Time {time < 10 ? "0" + time + ":00" : time + ":00"}</p>
<p>Temperature: {temperature} Celcius</p>
<p>Feel like temperature: {feelLikeTemperature} Celcius</p>
<p>Wind: {wind} mph</p>
<p>Weather Type: {weatherText}</p>
<p>Visibility: {visibility}</p>
<p>Max UV index: {UV}</p>
<p>Precipitation Probability: {pop} %</p>
</div>
);
}
export default Hours;