【发布时间】:2018-09-12 22:32:03
【问题描述】:
我收到“TypeError: Cannot read property 'map' of undefined”。不知道我在哪里出错了。在 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
}),
【问题讨论】:
-
它是说
this.props.meals是未定义的——这只能意味着你在渲染<Dashboard/>时没有传入任何meals属性。看不到您在哪里进行检查以进行检查,但没有其他解释。 -
好吧,我以为我是在底部的 mapStateToProps 下这样做的。看看我的 dailyLogsReducer 会有帮助吗?
-
抱歉,我错过了@D Graves。恐怕我只涉足过 React,从未使用过 Redux(尽管不久前我已经阅读过它的文档),所以目前这有点过头了。我要说的一件事,刚刚再次快速检查,“reducer”应该是一个函数(它接受一个状态和一个动作并返回一个新状态),所以我不确定你的
dailyLogsReducer有什么dailyLogs属性。如果没有,那就可以解释为什么您的meals属性未定义。希望比我更有知识的人能够提供帮助! -
分享你的reducer,如果你结合其中的几个,你的combine reducer配置肯定会有所帮助。另外,这些数据是否来自异步操作?
-
你能用 Redux 开发工具以某种方式跟踪你的状态吗?非常好用,可以考虑使用。尝试在此组件中记录您的状态。不要打开一个状态,只需打开整个状态,例如:
const mapStateToProps = state => ({ state });然后尝试记录它console.log(this.props.state);
标签: javascript reactjs redux