當我點擊重置按鈕時沒有任何反應。我不知道如何解決這個問題,你們有什么見解嗎?謝謝!如果我需要添加更多資訊,請告訴我。我試圖讓它到我可以點擊排序的地方,然后重置回原始顯示。非常感謝您!
const ToyList = (props) => {
const [sortedToys, setSortedToys] = useState(false)
const dispatch = useDispatch()
// imitates componentdidmount because it runs right away as soon as the component loads
useEffect(() => {
dispatch(fetchToys())
},[dispatch])
const sortToys = (toys) => {
if (sortedToys === true) {
return toys.sort( (toyA, toyB) => toyA.name.localeCompare(toyB.name))
}
if (sortedToys === false) {
return toys
} else {
return toys }}
function HandleSortOptionChange() {
setSortedToys(true)
}
function HandleSortOptionChangeFalse(e) {
setSortedToys(false)
}
return (
<div>
<div className="sortDiv">
<Button className="m-3" value="toy" onClick={HandleSortOptionChange}>Toys A-Z</Button>
<Button className="m-3" value="toy" onClick={HandleSortOptionChangeFalse}>Reset</Button>
</div>
<div>
</div>
{props.toys ? sortToys(props.toys).map(toy =>
<Container fluid>
<Row>
<Col key={toy.id}>
<Card style={{ width: '17rem' }} className='text-center'>
<Link to={`/toys/${toy.id}`}>{toy.name}
<Card.Img variant='top' src={toy.image_url} alt="toyimage" width="300" height="300" /></Link>
</Card>
</Col>
</Row>
</Container>
)
: <h2> Loading </h2>}
</div>
)
}
const mapStateToProps = (state) =>
({ toys: state.toys })
export default connect(mapStateToProps, {fetchToys})(ToyList)
uj5u.com熱心網友回復:
.sort 會改變原始陣列,因此如果 sortedToys 設定為 true,原始玩具陣列始終會排序,因此即使您在 false 時回傳玩具,它仍然會被排序。
uj5u.com熱心網友回復:
您不應該需要 sortToys,而且最好讓組件回傳 JSX;這是一種重新格式化的方式,您不需要此調度并且可以對玩具狀態本身使用 useEffect 。
const ToyList = (props) => {
const [toys, setToys] = useState([]);
const [sortToys, setSortToys] = useState(false);
const [startingToys, setStartingToys] = useState([]);
// On launch we can save the inital order to state
useEffect(() => {
// Set the toys
setToys(fetchToys());
// Save this ordering
setStartingToys(toys);
}, []);
// Whenever sortToys changes, we can also change toys
// thus re-rendering the list in the order you want
useEffect(() => {
if (sortToys) {
setToys(toys.sort((a, b) => a.name.localCompare(b.name)));
} else {
setToys(startingToys);
}
}, [sortToys]);
// Function to change the sort
const handleSortChange = () => setSortToys(() => !sortToys);
return (
<>
{/* Your JSX Here */}
</>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/379338.html
上一篇:如何呼叫這個添加函式
