我正在创建一个图书跟踪应用程序,该程序可以通过ajax获取图书并将其整理在书架上,我有很多组件,但是我在其中两个(AllShelves和BookShelf)之间存在问题,我很困惑,书架标题呈现在正确的顺序(如书架阵列中的顺序),当我尝试在相应的书架上排列书籍时,我的问题就开始了,我需要shelfName来执行此操作,我在mapStateToProps中过滤了我的书,但是当我在控制台中登录了shelfName时,我却以错误的书架结尾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);
那么这里的问题是什么,为什么不按未正确的顺序(如标题)登录架子名称项目呢?
最佳答案
尝试以下操作:(我简化了一些代码,并专注于我们需要解决的主要问题)
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
如果要访问
mapStateToProps()
函数内部传递的属性,请执行此操作。有关更多信息,您可以在这里找到它:mapStateToProps(state, [ownProps]): stateProps