简体   繁体   English

从connect(mapStateToProps)获取状态>未定义

[英]getting state from connect(mapStateToProps) > UNDEFINED

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 该项目的其余部分在我的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. book.idprops.match.params.id类型不同的情况下, ===将失败之前,我遇到了与此有关的问题。 The params values are always strings - maybe try parseInt(props.match.params.id) or == comparison (with type coercion). params值始终是字符串-可以尝试parseInt(props.match.params.id)==比较(强制类型)。

I managed to found where was my mistake. 我设法找到我的错误在哪里。

In the component BookListItem: 在组件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 不幸的是,在$ {id}之前,我使用了冒号{ /edit/:${id} },因此book.id和props.match.params.id无法匹配

Update the Link in the BookListItem . 更新BookListItemLink You don't need the : before ${id} . 您不需要${id}之前的 The : is causing the problem. 引起了问题。

<Link to={`/edit/${id}`}><h2>{title}</h2></Link>

In the EditBook component return the following EditBook组件中,返回以下内容

<BookForm {...props}></BookForm>

In the BookForm constructor set the state from props.book BookForm constructor设置从国家props.book

this.state = { ...props.book }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM