【发布时间】:2021-12-11 07:41:29
【问题描述】:
当我尝试加载我的玩具列表时出现此错误:
Unhandled Rejection (TypeError): dispatch is not a function react js
当我刷新页面时,它会显示列表片刻,然后出现错误。我已经在谷歌上搜索了几个小时,老实说,我不知道我做错了什么。我的目标是能够按下排序按钮并能够按字母顺序对玩具进行排序,然后再次按下以显示未排序的玩具。
如果您有任何建议,请通过我的方式发送。谢谢!
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 (
<div>
<div className="sortDiv">
<Button className="m-3" value="toy" onClick={handleSortChange}>Toys A-Z</Button>
</div>
<div>
</div>
{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> ) }
</div>
)
}
export default ToyList
我的 fetchToys 操作:
export function fetchToys() {
return (dispatch) => {
fetch('http://localhost:3000/api/v1/toys')
.then(response => response.json())
.then(toys=> dispatch({
type: 'FETCH_TOYS',
payload: toys
}))
}
}
【问题讨论】:
-
所以问题出在我的 fetchToys 操作中?我看不出问题出在哪里......直到最近我才遇到任何问题。
标签: javascript reactjs react-redux