I make todo app with React.js + Redux.
But, I have occurs error "TypeError: this.props.posts.map is not a function"
My 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);
My List component :
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>
);
}
}
My reducer :
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
}
];
Why does the error occur? I set console.log, but it is undefined ...
----EDIT
codesandbox link: https://codesandbox.io/s/x91zl9v78p
You don't have a default
branch in your switch
statement in your reducer, which will make it so undefined
is returned by default.
You could add a default
branch that just returns the state.
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;
}
}
You must also make sure that you give state.post
as allPost
, and not the entire Redux state. There is also no need for you to use connect
on the Item
component because you give the title
and content
as props anyway.
const mapStateToProps = state => {
return {
allPosts: state.post
};
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.