我使用React.js + Redux制作待办事项应用程序。
但是,我发生了错误“ TypeError:this.props.posts.map不是函数”
我的App.js:
class App extends Component {
render() {
return (
<div className="App">
<Input />
<List posts={this.props.allPosts} />
</div>
);
}
}
const mapStateToProps = state => {
return {
allPosts: state
};
};
export default connect(
mapStateToProps,
null
)(App);
我的列表组件:
class List extends Component {
render() {
console.log(this.props.posts);
return (
<div>
<ul>
{this.props.posts.map((post, index) => (
<Item {...post} key={index} />
))}
</ul>
</div>
);
}
}
我的减速机:
const initialState = [];
export default function Post(state = initialState, action) {
switch (action.type) {
case ADD_POST:
return [
...state,
{
id: action.id,
title: action.title,
content: action.content
}
];
为什么会发生错误?我设置了console.log,但是它是未定义的...
- - 编辑
codesandbox链接:https ://codesandbox.io/s/x91zl9v78p
您在化简器default
中的switch
语句中没有分支,这将使其undefined
默认情况下返回。
您可以添加default
仅返回状态的分支。
const initialState = [];
export default function Post(state = initialState, action) {
switch (action.type) {
case ADD_POST:
return [
...state,
{
id: action.id,
title: action.title,
content: action.content
}
];
default:
return state;
}
}
您还必须确保输入state.post
as allPost
,而不是整个Redux状态。也不需要connect
在Item
组件上使用,因为无论如何您都会提供title
和content
作为道具。
const mapStateToProps = state => {
return {
allPosts: state.post
};
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句