TypeError: Cannot read property 'touristRoutes' of undefined

来源:9-7 【中间件】使用redux-thunk中间价实现异步action

慕函数4298367

2021-03-03

export const HomePage:React.FC=()=>{
const loading=useSelector(state=>state.recommendProduct.loading)
const productList =useSelector(state=>state.recommendProduct.productList)
const dispatch=useDispatch()
useEffect(()=>{
try {
dispatch(fetchRecommendProductStartActionCreator())
const feacthdate=async()=>{
const {data}=await axios.get(“http://123.56.149.216:8080/api/productCollections",{headers:{“x-icode”:"472DA4444926CAB2”}})
dispatch(fetchRecommendProductSuccessActionCreator(data))
}
feacthdate()
} catch (e) {
dispatch(fetchRecommendProductFailActionCreator(e.message))
}
},[] )
console.log(“productList”,productList)
console.log(“productList”,productList[0].touristRoutes)

老师用useSelector获取store数据后 console.log(“productList”,productList) 是可以取到数据的,但是访问数组下的某个字段是报TypeError: Cannot read property ‘touristRoutes’ of undefined的错误,我需要在哪里去定义productList的类型呢?

写回答

1回答

阿莱克斯刘

2021-03-04

hello 你好,

console.log(“productList”,productList)
console.log(“productList”,productList[0].touristRoutes)

直接放在组件中是组件中是读不到数据的,因为HomePage在启动的时候可能还没有取得productList的数据,那么这个时候访问productList[0].touristRoutes自然会报错,因为productList还不存在。

想正常读取productList数据,我们必须在副作用函数中进行。也就是应该放在useEffect 的try中feacthdate()函数调用的后面。

0
2
阿莱克斯刘
回复
慕函数4298367
第一个问题:“那这样的话 函数是组件了用什么方法处理数组在useEffect执行后才会有值的情况呢?” 需要在渲染的时候做一定的判断,简单来说就是在没有数据或正在请求数据的时候转菊花就可以了。课程中会有详细的讲解。 第二个问题:“直接用{}就报上面的错误,但是用{productList.map(p=> )} 去渲染就正常这个是为什么呢” 这是因为,你可以尝试一下答应productList.map的输出,如果productList没有数据,那么它的输出是空列表,空列表不会报错;而直接访问productList[0]的时候,如果productList没有数据,那么访问它的第一个元素当然会报错。
2021-03-05
共2条回复

React18 系统精讲 结合TS打造旅游电商平台

React18 精讲 + 结合 TS 实战 + 热门业务开发,获取必备技能

1993 学习 · 1015 问题

查看课程