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

标签 javascript reactjs redux

我正在创建一个书籍跟踪应用程序,它通过ajax获取书籍并将它们组织在书架上,我有很多组件,但我在其中两个组件之间存在问题,AllShelves和BookShelf,我很困惑,书架标题以书架数组中的正确顺序呈现,当我尝试将书籍排列在相应的书架上时,我的问题开始了,我需要shelfName来做到这一点,我在mapStateToProps中过滤了我的书籍,但当我控制台时,我以错误的书架中的书籍结束在mapStateToProps中记录了shelfName我得到了这个订单

//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);

那么这里的问题是什么,为什么不以正确的顺序记录shelfName项目,如标题。

最佳答案

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

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

关于javascript - 为什么我的书没有排列在正确的书架上(React-Redux)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52600796/

相关文章:

CSS/HTML - 在内容之前滚动标题

javascript - react : multiple JSX templates for one single component

reactjs - Redux - API 被多次调用 (Redux Thunk)

reactjs - 无法使用带有功能组件的引用从父函数调用子函数

javascript - Angular JS 动态模型

javascript - 优化刻度位置以最大限度地减少图表顶部浪费的空间

javascript - 创建混合高度合理的标题?

javascript - 来自上下文提供者的 Prop : Property 'xxx' does not exist on type 'IntrinsicAttributes & InterfaceProps'

javascript - ReduxForm - enableReinitialize 不更新嵌套 FieldArrays 中的值

javascript - 将 Promises 与 mongoose 一起使用的正确方法是什么?