I am kind of struggling to get the state of book, when I log the props I get book: undefined.
Any tips?
import React from 'react';
import { connect } from 'react-redux';
import BookForm from './BookForm';
const EditBook = (props) => {
console.log(props)
return (
<div>
hello
</div>
);
};
const mapStateToProps = (state, props) => {
return {
book: state.books.find((book) => book.id === props.match.params.id)
};
};
export default connect(mapStateToProps)(EditBook);
Rest of the project is on my Github: https://github.com/bananafreak/bookshelf
I've ran into issues with this before where ===
will fail because the types of book.id
and props.match.params.id
are different. The params
values are always strings - maybe try parseInt(props.match.params.id)
or ==
comparison (with type coercion).
I managed to found where was my mistake.
In the component BookListItem:
import React from 'react';
import { Link } from 'react-router-dom';
const BookListItem = ({ author, title, genre, text, id, pages }) => (
<div>
<Link to={`/edit/${id}`}><h2>{title}</h2></Link>
<h3>by: {author}</h3>
<p>{genre}</p>
{pages > 0 && <p>{pages} pages</p>}
<p>{text}</p>
<p>-------------------------------</p>
</div>
);
export default BookListItem;
Before the ${id} I had unfortunately colon { /edit/:${id}
} so then book.id and props.match.params.id could not match
Update the Link
in the BookListItem
. You don't need the : before ${id}
. The : is causing the problem.
<Link to={`/edit/${id}`}><h2>{title}</h2></Link>
In the EditBook
component return the following
<BookForm {...props}></BookForm>
In the BookForm
constructor
set the state from props.book
this.state = { ...props.book }
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.