简体   繁体   中英

Unhandled Rejection (TypeError): dispatch is not a function react js

I am having this error when I try to load my list of toys:

Unhandled Rejection (TypeError): dispatch is not a function react js

When I refresh the page, it shows the list for just a moment and then the error appears. I have been googling for hours now and I honestly don't know what I am doing wrong. My goal is to be able to press a sort button and be able to sort the toys alphabetically, and then press it again to show the unordered toys.

If you have any advice, please send it my way. Thank you!

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

My fetchToys action:

export function fetchToys() {
    return (dispatch) => {
    fetch('http://localhost:3000/api/v1/toys')
    .then(response => response.json())
    .then(toys=> dispatch({
        type: 'FETCH_TOYS', 
        payload: toys
    }))
    }
}

export function fetchToys() is wrong. try this: export function fetchToys(dispatch)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM