[英]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.