尝试访问react道具数据时无法访问该数据.Getting TypeError错误


Redux操作创建者被解雇,并向我的服务器发出获取请求,然后将数据返回给ReactLead组件。但我可以访问数据来更新UI。当我对数据进行控制台日志记录时,它显示这是一个数组对象,但当我尝试使用map()访问组件中的数据时,它会将lead-props返回为undefined。可能是因为我为传入状态设置了类型检查吗?

此外,当我注释掉类型检查对象集并尝试访问数组对象数据时,我会得到一个TypeError错误:TypeError: props.leads is undefined,但我可以控制台记录它,它会显示出来。

为什么当我试图访问undefined数据,但却登录到浏览器解释器,而我只在控制台上记录它时,我会得到它?。

下面的SOUCE代码

Redux操作:

import GET_LEADS from './types';
// GET LEADS
export const getLeads = () => (dispatch) => {
fetch('/api/leads/')
.then((response) => {
if (response.status != 200) {
throw new Error(response.statusText);
}
return response.json();
})
.then((res) => {
dispatch({
type: GET_LEADS,
payload: res
});
})
.catch((err) => {
console.log(err)
});
}

Redux减速器

引线减速器:

import { GET_LEADS } from '../actions/types';
const initialState = {
leads: []
};

export default function leads(state=initialState, action) {
switch (action.types) {
case GET_LEADS:
return {
...state,
leads: action.payload
};
default:
return state;
}
}

组合式减速器:

import { combineReducers } from 'redux';
import leads from './leads';
const rootReducer = combineReducers({
leads: leads
});
export default rootReducer;

React Leads组件(容器,因为它连接到redux(:

import React, {useEffect} from 'react';
import {connect} from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import { getLeads } from '../../actions/leads';
export function Lead(props) {
useEffect(() => {
props.getLeads();
},[]);
return (
<React.Fragment>
<div className="table-responsive-lg">
<table className="table table-hover table-sm shadow-sm">
<thead>
<tr>
<th scope='col'>ID</th>
<th scope='col'>Title</th>
<th scope='col'>F-Name</th>
<th scope='col'>M-Name</th>
<th scope='col'>L-Name</th>
<th scope='col'>Phone</th>
<th scope='col'>Company</th>
<th scope='col'>Website</th>
<th scope='col'>Address</th>
<th scope='col'>Addr_1</th>
<th scope='col'>Addr_2</th>
<th scope='col'>Addr City</th>
<th scope='col'>Addr State</th>
<th scope='col'>Addr Country</th>
<th scope='col'>Sale Rep</th>
<th scope='col'>Status</th>
<th scope='col'>Priority</th>
</tr>
</thead>
<tbody>
{props.leads[0].map(lead => (   // <---- TypeError: props.leads is undefined
<tr key={lead.id}>
<td>{lead.id}</td>
</tr>
))}
{console.log(props.leads)}
</tbody>
</table>
</div>
</React.Fragment>
);
}
Lead.propTypes = {
leads: PropTypes.array.isRequired, // <--- type checking for array object
getLeads: PropTypes.func.isRequired
};

const mapDispatchToProps = (dispatch) => bindActionCreators({getLeads}, dispatch);
const mapStateToProps = (state) => ({ leads: state.leads.leads });
export default connect(mapStateToProps, mapDispatchToProps)(Lead);

试试这个:

tbody标签中

{props.leads && props.leads[0].map(  
<tr key={lead.id}>
<td>{lead.id}</td>
</tr>
))}

我认为您在switch语句中输入了错误,应该是switch(action.type)而没有的,这就是为什么当触发操作时,它在reducer中找不到相应的操作类型,并且数据没有加载到reduce存储

最新更新