[英]Can not access react props data when I try to access it. Getting TypeError error
Redux 动作创建者被触发并向我的服务器发出 fetch 请求,然后将数据返回给 React Lead
组件。 但是我可以访问数据来更新 UI。 当我控制台记录数据时,它显示这是一个数组对象,但是当我尝试使用map()
访问组件中的数据时,它会将引线道具返回为undefined
。 可能是因为我为传入状态设置的类型检查?
此外,当我注释掉类型检查对象集并尝试访问数组对象数据时,我收到一个TypeError
错误: TypeError: props.leads is undefined
,但我可以控制台记录它并显示它。
为什么当我尝试访问它时会得到一个undefined
数据,但当我只通过控制台记录它时会记录到浏览器解释器?。
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)
});
}
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;
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)
没有 's,这就是为什么当触发动作时它在减速器中找不到对应的动作类型并且数据没有加载到 redux 存储
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.