【问题标题】:Unhandled Rejection (TypeError): dispatch is not a function react js未处理的拒绝(TypeError):调度不是一个函数反应js
【发布时间】: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


【解决方案1】:

export function fetchToys() 是错误的。 试试这个:export function fetchToys(dispatch)

【讨论】:

  • 见“Explaining entirely code-based answers”。虽然这在技术上可能是正确的,但它并没有解释为什么它可以解决问题或应该是选择的答案。我们应该在帮助解决问题的同时进行教育。
猜你喜欢
  • 1970-01-01
  • 2018-12-09
  • 2021-10-14
  • 2020-11-16
  • 2020-05-06
  • 2019-10-27
  • 2020-09-26
  • 2021-04-16
  • 2021-03-09
相关资源
最近更新 更多