我收到“ TypeError:无法读取未定义的属性'map'”。不知道我在哪里出错了。关于React,我还是很新,所以我不知道我是否缺少什么。当我尝试调用this.props.meals.map时,这给了我错误
export class Dashboard extends React.Component {
componentDidMount() {
this.props.dispatch(fetchProtectedData());
this.props.dispatch(retrieveDailyLogs())
.then(results => {
return this.props.dispatch(getDailyLogs(results));
})
}
getId(id) {
console.log('test');
this.props.dispatch(removeDay(id))
this.props.dispatch(retrieveDailyLogs())
.then(results => {
return this.props.dispatch(getDailyLogs(results));
});
}
render() {
const dailyLogs = this.props.meals.map((day, index) =>
<li className="card" key={index}>
<Card handleClick={(id) => this.getId(id)} {...day} />
</li>
)
return (
<section className="dashboard-container">
<h1>Dashboard</h1>
<Link className="log-day-btn" to="/dailylogs">Log Meals</Link>
<ul className="meal-list">
{dailyLogs}
</ul>
</section>
);
}
}
const mapStateToProps = state => ({
meals: state.dailyLogsReducer.dailyLogs
});
export default requiresLogin()(connect(mapStateToProps)(Dashboard));
这是我的减速机,以防万一
import {ADD_DAY, GET_DAILYLOGS, DELETE_DAY} from '../actions/dailyLogs';
const initialState = {
dailyLogs: [{
date: null,
meal1: null,
meal2: null,
meal3: null,
snack: null,
totalCalories: null,
}]
};
export default function reducer(state = initialState, action) {
if (action.type === ADD_DAY) {
return Object.assign({}, state, {
dailyLogs: [...state.dailyLogs, {
date: action.date,
meal1: action.meal1,
meal2: action.meal2,
meal3: action.meal3,
snack: action.snack,
totalCalories: action.totalCalories
}]
});
}
else if(action.type === GET_DAILYLOGS) {
return Object.assign({}, state, {
dailyLogs: action.dailyLogs.dailyLogs
})
}
else if(action.type === DELETE_DAY) {
return 'STATE';
}
return state;
}
这是我的CombineReducer。它在我的store.js中
combineReducers({
form: formReducer,
auth: authReducer,
protectedData: protectedDataReducer,
dailyLogsReducer
}),
渲染方法可以在componentDidMount之前运行。如果在render方法运行时尚未定义this.props.meals,则组件将引发您看到的错误。
您可以在使用映射对象之前检查其是否存在
this.props.meals && this.props.meals.map( // your code here )
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句