![](/img/trans.png)
[英]TypeError: Cannot read property 'data' of undefined - can't access Object "props" beyond certain level in Reactjs
[英]i can see props coming from action(redux) in console logs but can't access on window. Giving TypeError: Cannot read prop 'rest' of undefined
因此,我对所有的react和redux都是陌生的,并且在经过几次讨论和博客之后,我正在尝试创建react-redux应用程序。 我正在点击一个API来获取一些数据。
减速器看起来像这样:
const initialState ={
rest: null,
rests: null,
loading: false
}
export default function(state = initialState, action){
switch (action.type){
case REST_LOADING:
return{
...state,
loading: true
}
case GET_REST:
return {
...state,
rest: action.payload,
loading: false
}
行动:
export const getCurrentRest = name =>
dispatch(setRestLoading());
axios.get(`/api/restaurant/rest/${name}`)
.then(res =>
dispatch({
type: GET_REST,
payload: res.data
})
)
.catch(err =>
dispatch({
type: GET_REST,
payload: {}
})
);
}
现在,我在类似这样的页面上调用此操作:
class CafeMenu extends Component {
name = this.props.match.params.id;
constructor(props) {
super(props);
}
componentDidMount() {
this.props.getCurrentRest(this.name);
}
在渲染部分,我进行了一些分解。 原来:
const {rest, loading} = this.props.rest;
后来我将其更改为
const {rest} = this.porps.rest;
现在,我可以在控制台日志中看到数据,并且在redux devtools扩展中可以看到状态更改,但是当我尝试通过rest.name或this.rest.rest.name对其进行访问而不进行破坏时,它将引发typeError,例如无法读取属性'rest'未定义。 我尝试了一切,但无法弄清楚我做错了什么,以及如何进一步解决并坚持下去。
最初我也做了类似的事情:
if(rest === undefined || null){
<h1> loading</h1>
}
else{
reder...
并且this.props.rest的console.log是
{rest: Array(1), rests:null, loading: false}
loading: false
rest: Array(1)
0:
email: "something@abc.com"
loc: {long: "23.34", lat: "43"}
loc_name: "abc"
menu: []
name: "xyz"
...
看起来您没有正确破坏道具。
也有一个错字这里porps 而不是道具 。
const {rest} = this.porps.rest;
这可能是引发typeError的原因。
现在用于破坏部分。 假设这是您的道具结构
{rest: Array(1), rests:null, loading: false}
loading: false
rest: Array(1)
0:
email: "something@abc.com"
loc: {long: "23.34", lat: "43"}
loc_name: "abc"
menu: []
name: "xyz"
rests: null
这是通过破坏来访问的:
const { loading, rest, rests } = this.props
值将是
loading = false
rest = Array(1)
0:
email: "something@abc.com"
loc: {long: "23.34", lat: "43"}
loc_name: "abc"
menu: []
name: "xyz"
rests = null
现在,由于rest
是一个数组,要访问第一个餐厅名称, rest[0].name
应该给您"xyz"
。
让我知道是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.