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