【发布时间】:2021-08-22 07:03:44
【问题描述】:
您好,我正在创建一个应用程序,用户可以在其中搜索一本书并将其放在书架上,具体取决于用户点击的书架。目前,用户可以键入查询,并且可以显示许多结果。用户可以打开一本书的下拉菜单并单击书架(在下拉菜单中)以选择该书的书架。
我想调用一个方法来更新一本书的书架。但是,只有当shelfType 是硬编码时它才有效(shelfTypes 是'wantToRead'、'read'、'currentlyReading')。我想要发生的是用户单击一个架子,并且该架子被设置为 SearchPage 中的本地状态变量shelfType。然后一旦shelfType改变,更新书架的方法就会运行(它对后端进行API调用)。
但由于某些奇怪的原因,我只能在将架子类型硬编码到更新方法中时才能更新架子,而不是在使用状态架子类型的值时。我究竟做错了什么?我希望这个问题有意义。
SearchPage.js
import React, { useEffect, useState } from 'react';
import { BsArrowLeftShort } from 'react-icons/bs';
import SearchBar from '../components/SearchBar';
import { search, update, getAll } from '../api/BooksAPI';
import Book from '../components/Book';
const SearchPage = () => {
const [query, setQuery] = useState('');
const [data, setData] = useState([]);
const handleChange = (e) => {
setQuery(e.target.value);
};
useEffect(() => {
const bookSearch = setTimeout(() => {
if (query.length > 0) {
search(query).then((res) => {
if (res.length > 0) {
setData(res);
} else setData([]);
});
} else {
setData([]); // make sure data is not undefined
}
}, 1000);
return () => clearTimeout(bookSearch);
}, [query]);
const [shelfType, setShelfType] = useState('None');
const [currentBook, setCurrentBook] = useState({});
const doSomethingWithBookAndShelf = (book, shelf) => {
setShelfType(shelf);
setCurrentBook(book);
};
useEffect(() => {
//following line doesn't update like this, but I want it to work like this
update(currentBook, shelfType).then((res) => console.log(res));
// update works if I run update(currentBook, 'wantToRead').then((res) => console.log(res));
getAll().then((res) => console.log(res));
}, [shelfType]);
return (
<div>
<SearchBar
type="text"
searchValue={query}
placeholder="Search for a book"
icon={<BsArrowLeftShort />}
handleChange={handleChange}
/>
<div className="book-list">
{data !== []
? data.map((book) => (
<Book
book={book}
key={book.id}
doSomethingWithBookAndShelf={doSomethingWithBookAndShelf}
/>
))
: 'ok'}
</div>
</div>
);
};
export default SearchPage;
Book.js
import React from 'react';
import PropTypes from 'prop-types';
import ButtonDropDown from './ButtonDropDown';
const Book = ({ book, doSomethingWithBookAndShelf }) => {
return (
<div className="book">
<img
src={book.imageLinks.thumbnail}
alt={book.title}
className="book-thumbnail"
/>
<ButtonDropDown
choices={['Currently Reading', 'Want to Read', 'Read', 'None']}
onSelectChoice={(choice) => {
// book came from the component props
doSomethingWithBookAndShelf(book, choice);
}}
/>
<div className="book-title">{book.title}</div>
<div className="book-authors">{book.authors}</div>
</div>
);
};
Book.propTypes = {
doSomethingWithBookAndShelf: PropTypes.func.isRequired,
book: PropTypes.shape({
imageLinks: PropTypes.shape({
thumbnail: PropTypes.string.isRequired,
}),
title: PropTypes.string.isRequired,
authors: PropTypes.arrayOf(PropTypes.string),
}).isRequired,
};
export default Book;
ButtonDropDown.js
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { BsFillCaretDownFill } from 'react-icons/bs';
const ButtonDropDown = ({ choices, label, onSelectChoice }) => {
const [active, setActive] = useState(false);
const toggleClass = () => {
setActive(!active);
};
return (
<div className="dropdown">
<button
type="button"
className="dropbtn"
onFocus={toggleClass}
onBlur={toggleClass}
>
<BsFillCaretDownFill />
</button>
<div
id="myDropdown"
className={`dropdown-content ${active ? `show` : `hide`}`}
>
<div className="dropdown-label">{label}</div>
{choices.map((choice, index) => (
<button
// eslint-disable-next-line react/no-array-index-key
key={index}
className="dropdown-choice"
onClick={() => {
// we create an specific callback for each item
onSelectChoice(choice);
}}
type="button"
value={choice}
>
{choice}
</button>
))}
</div>
</div>
);
};
ButtonDropDown.propTypes = {
choices: PropTypes.arrayOf(PropTypes.string).isRequired,
label: PropTypes.string,
onSelectChoice: PropTypes.func.isRequired,
};
ButtonDropDown.defaultProps = {
label: 'Move to...',
};
export default ButtonDropDown;
【问题讨论】:
-
除了硬编码,你没有从任何地方获取
shelfType数据,你需要获取数据 -
但是我使用 doSomethingWithBookAndShelf 获取书架,然后我使用状态更新器函数将该值设置为shelfType
-
useEffect(() => { update(currentBook, shelfType).then((res) => console.log(res)); getAll().then((res) => console.log(res)); }, [shelfType]);对currentBook的引用过时
标签: javascript reactjs state use-effect prop