【发布时间】:2021-02-27 10:41:09
【问题描述】:
我想对我的 API 请求进行排序。但是当我第一次单击该选项时,什么也没有发生。当我单击另一个选项时,仍然没有。当我第二次单击另一个选项时,它开始工作。
import { useEffect, useState } from "react";
//style
import styled from "styled-components";
import { motion } from "framer-motion";
import Header from "../components/Header";
//link
import { Link } from "react-router-dom";
//redux
import { useDispatch, useSelector } from "react-redux";
import { loadPreSortB } from "../actions/preSortAction";
//dropdown
const TabakMarken = () => {
//Fetch
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadPreSortB(sortValue));
}, [dispatch]);
//get that data back
const { brand } = useSelector((state) => state.preSort);
//dropdown
const [sortValue, setSortValue] = useState("ASC");
const handleSortValue = (e) => {
setSortValue(e.target.value);
dispatch(loadPreSortB(sortValue));
};
return (
<SortenWrap>
<Header />
<SubHead>
<h2>Marke auswählen.</h2>
<select defaultValue="{sortValue}" onChange={handleSortValue}>
<option value="DESC">Alphabetisch A-Z</option>
<option value="ASC">Alphabetisch Z-A</option>
</select>
</SubHead>
...```
【问题讨论】:
-
欢迎来到 StackOverflow。我建议你编写一些缺少的函数(动作创建者、reducer 和 store)来提供更多信息。无论如何,我鼓励您不要将来自一个组件 (TabakMarken) 的本地状态与来自 redux 的全局状态混合在一起。您正在根据本地状态 (sortValue) 的状态调度操作。为什么不删除该状态并只写 dispatch(loadPreSortB(e.target.value))?我建议这样做,因为不能保证在调用 dispatch(sortValue) 时 sortValue 会发生变化。
-
解决了我的问题,谢谢!
标签: reactjs api select dropdown