javascript - TypeError: Cannot read properties of undefined (reading 'name') - React , redux-toolkit
问题描述
我使用 react-redux Toolkit 从 API 获取数据。想要在页面渲染时显示默认城市天气数据,但它给出了错误
TypeError:无法读取未定义的属性(读取“名称”)
输出 - > index.js 的空数组比 WeatherSlice.js 的 API 输出
export const fetchDefault = createAsyncThunk('weather/getWeather', async (selectedCity) => {
const res = await axios(`http://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=${selectedCity}&days=10&aqi=no&alerts=no
`)
return res.data
});
<Typography className="label" variant="h5" sx={{pb:5}} component="div">
{getCity.location.name} // GivesTypeError
</Typography>
主页组件
const getCity = useSelector((state) => state.weather.item);
useEffect(() => {
dispatch(fetchDefault(selectedCity))
console.log()
}, [dispatch])
应用程序.js
<Switch>
<Route path="/about" component={About} >
<About />
</Route>
<Route path="/" component={Home}>
<Home />
</Route>
</Switch>
Store.js
export const store = configureStore({
reducer: {
weather : weatherSlice.reducer,
},
})
WeatherSlice.js
export const weatherSlice = createSlice({
name: "weather",
initialState : {
item : [],
},
reducers:{},
extraReducers:{
[fetchDefault.fulfilled]: (state , action) => {
state.item = action.payload;
console.log(state.item)
},
[fetchDefault.pending]: (state , action) => {
console.log("sadsad")
}
}
解决方案
我检查了您使用的 api ( https://api.weatherapi.com/v1/forecast.json?key=ebb6c0feefc646f6aa6124922211211&q=Istanbul&days=10&aqi=no&alerts=no ) 看看它返回了什么。
响应数据是具有以下字段的对象:位置、当前和预测。
所以起初,我认为“项目”的初始状态不应该是一个空数组,因为 api 不返回一个数组,而是它应该是未定义或空对象。
那么,TypeError 存在的主要原因是您无法检索数据或无法填写状态中的项目。您应该检查从 api 返回的数据。你能成功检索数据并用它填充状态吗?
TypeError 的原因:如果您有一个空数组或空对象并尝试通过此元素访问字段(如 item.location),则不会显示错误,但如果您尝试访问字段的字段(如 item.location)。 location.name) 发生 TypeError。
在组件之前检查对象也会更安全。像:
// can be undefined comparison or getCity.length > 0 etc
{getCity !== undefined && (
<Typography className="label" variant="h5" sx={{pb:5}} component="div">
{getCity.location.name} // GivesTypeError
</Typography>
)}
推荐阅读
- r - UseMethod(“select_”)中的Rmarkdown错误退出错误:没有适用于“select_”的适用方法应用于类“函数”的对象
- node.js - 如何使用电报机器人回复引用消息?
- resilience4j - 如何在 Resilience4J 中实现多个具有相同配置的断路器
- angular - 通过 formGroup + ngModel 使用的角度反应式表单验证:弃用的致命警告 + 移除支持?
- owl - 从“.owl”文件导入命名空间并在 RDFLIB 图中使用术语
- rest - 在 ElasticSearch RestHighLevelClient 对象中出现超时错误。如何延长30000毫秒的时间限制?
- python - 将 emty 列表 `[]` 转换为 `[0]` 熊猫数据框
- reactjs - google 没有在 @react-google-maps/api 的 Gatsby js 应用程序中定义
- jestjs - Jest:编写所有需要首先断言某些步骤的测试的正确方法是什么?
- android - 如何在 MVVM 模型中与服务通信