【发布时间】:2019-11-29 23:34:02
【问题描述】:
我已经设置了 react/redux,这样当组件挂载时,它会呈现信息。当我通过控制台记录 this.props.heroes.data 时,我得到一个值 [{id:1,heroname:'Batman',realname:'Bruce Wayne'},{id:2,heroname:'Nightwing',realname:'Richard Grayson'}]。当我尝试映射this.props.hero.data 时,我得到一个undefined 语句并且console.log 变成一个空数组。
我的堆栈是 React、Redux、Express、PostgreSQL
我尝试使用 this.props.heroes 进行一些控制台日志,并且能够使用空数组从完全未定义变为未定义。
我的英雄组件页面:
class AllHeroes extends Component {
async componentDidMount() {
await this.props.getHeroes();
}
render() {
const heroes = this.props.heroes;
console.log("heroesreal", heroes);
console.log(typeof heroes);
if (!this.props.heroes) return "LOADING";
else {
return (
<div>
<h1>Placeholder</h1>
{heroes.data.map(hero => {
return <div key={hero.id}>{hero.heroname}</div>;
})}
</div>
);
}
}
}
const mapStateToProps = state => ({ heroes: state.heroes });
const mapDispatchToProps = dispatch => ({
getHeroes: () => dispatch(getHeroes())
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(AllHeroes);
我的英雄归来:
const GOT_HEROES = "GOT_HEROES";
const gotHeroes = heroes => ({ type: GOT_HEROES, heroes });
export const getHeroes = () => async dispatch => {
const { data } = await axios.get("/api/heroes");
dispatch(gotHeroes(data));
};
const heroesReducer = (heroes = [], action) => {
switch (action.type) {
case GOT_HEROES:
return action.heroes;
case DELETE_HERO:
const heroId = action.id;
return heroes.filter(hero => hero.id !== heroId);
default:
return heroes;
}
};
const combinedReducers = combineReducers({
heroes: heroesReducer,
villains: villainsReducer,
hero: heroReducer
// villain: villainReducer
});
我不相信我有任何商店连接问题,因为我之前遇到过错误,我通过在我的最顶层组件中放置一个提供程序和商店来修复它。
预期要呈现的页面:Batman Nightwing 但得到了undefined: []。提前感谢您的帮助!
【问题讨论】:
-
您能发布完整的控制台日志吗?
标签: javascript reactjs postgresql express react-redux