【发布时间】:2021-07-21 19:27:44
【问题描述】:
我正在构建天气应用程序,我的想法是将城市名称保存在 localStorage 中,将道具传递给子组件,然后使用地图进行迭代并在第一个子组件的单独子组件中显示每个子组件
问题是渲染时显示的数据加倍/三倍(取决于渲染发生时的组件)所以当我有例如伦敦市并添加柏林市时,它将渲染:
伦敦,伦敦,柏林
问题不在于 AddCity 组件,它工作正常,但在这种异步 setState/fetching 和映射的混合中
请看下面的代码
应用(父组件)
const App = () => {
const [cities, setCities] = useState([]);
const addCity = (newCity)=>{
console.log('adding')
setCities([...cities, newCity]);
let cityId = localStorage.length;
localStorage.setItem(`city${cityId}`, newCity);
}
useEffect(() => {
loadCityFromLocalStore()
}, [])
const loadCityFromLocalStore =()=>{
setCities([...cities, ...Object.values(localStorage)])
}
return (
<div>
<Header />
<AddCity addCity={addCity}/>
<DisplayWeather displayWeather={cities}/>
</div>
)
}
DisplayWeather(第一个孩子)
const DisplayWeather = ({displayWeather}) => {
const apiKey = '4c97ef52cb86a6fa1cff027ac4a37671';
const [fetchData, setFetchData] = useState([]);
useEffect(() => {
displayWeather.map(async city=>{
const res =await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`)
const data = await res.json();
setFetchData((fetchData=>[...fetchData , data]));
})
}, [displayWeather])
return (
<>
{fetchData.map(data=>(
<ul>
<Weather
data={data}/>
</ul>
))}
</>
)
}
天气组件
const Weather = ({data}) => {
return (
<li>
{data.name}
</li>
)
}
【问题讨论】:
标签: reactjs dictionary fetch