为什么我的书没有放在正确的书架上(React-Redux)?

时间:2018-10-02 01:09:17

标签: javascript reactjs redux

我正在创建一个图书跟踪应用程序,该程序可以通过ajax来获取图书并将其整理在书架上,我有很多组件,但是我在其中的两个书架(AllShelves和BookShelf)之间存在一个问题,我很困惑,书架标题以正确的顺序呈现(如书架阵列中的顺序),当我尝试在相应的书架上排列书籍时,我的问题就开始了,我需要shelfName来做到这一点,我在mapStateToProps中过滤了我的书,但是当我进行控制台操作时,我以错误的书架结尾我在mapStateToProps中记录了架子名称,我得到了这个订单

//read
//currentlyReading
//wantToRead

代替

//currentlyReading
//wantToRead
//read

甚至重复

这些是我的组成部分

第一个组件

import React, {Component} from 'react';
import BookShelf from './BookShelf'

const AllShelves = () => {

   const shelves = [
    {
      title: 'Currently Reading',
      shelfName: 'currentlyReading'
    },
    {
      title: 'Want to read',
      shelfName: 'wantToRead'
    }, 
    {
      title:'Read',
      shelfName: 'read'
    }
  ];

  return(
   <div>
    {shelves.map((shelf, index) => {
      return (
        <div className="shelf" key={index}>
          <h2>{shelf.title}</h2>
          <BookShelf 
            shelfName={shelf.shelfName}
          />
        </div>
      );
    })}
  </div>
 );
} 

export default AllShelves;

子组件

import React, { Component } from 'react';
import Book from './Book'
import {connect } from 'react-redux';


let shelfName = '';

const BookShelf = (props) => {

  shelfName = props.shelfName;

  return(
    <div className="book-shelf">
       {props.books.map(book => (
          <Book 
            key={book.id}
            book={book}
          />
        ))}
    </div>
  );
 }

const mapStateToProps = state => {
  console.log(shelfName)//read
                        //currentlyReading
                        //wantToRead
  return {
    books: state.filter(book => book.shelf === shelfName)
 }
}

export default connect(mapStateToProps, null)(BookShelf);

那么这里出了什么问题,为什么不按未正确的顺序(如标题)记录架子名称项目呢?

1 个答案:

答案 0 :(得分:1)

尝试一下:(我简化了一些代码,并专注于我们需要解决的主要问题)

import React from "react";
import { connect } from "react-redux";

const BookShelf = props => {
  const shelfName = props.shelfName;
  return <div>{shelfName}</div>;
};
const mapStateToProps = (state, ownProps) => {
  console.log(ownProps.shelfName);
  return ({

  });
};
export default connect(mapStateToProps)(BookShelf);

这是演示:https://codesandbox.io/s/p5jr57vw8j

demo

如果要访问mapStateToProps()函数内部传递的属性,请执行此操作。有关更多信息,您可以在这里找到:mapStateToProps(state, [ownProps]): stateProps