使用 useState 和获取请求从 onChange 选项下拉列表中检索值
Retrieving value from onChange option dropdown with useState and fetch request
我正在构建一个过滤器以根据所选选项显示值列表。数据由获取请求填充,然后映射到显示值。
这部分工作正常。但是我发现下拉菜单似乎没有注册 onChange 事件,因此没有从 null 更新值。
这是我的代码...
import ProductCard from "../ProductCard";
import "./style.css";
function ProductFilter(props) {
const [designerData, setDesignerData] = useState([]);
const [selectedDesigner, setSelectedDesigner] = useState(null);
useEffect(() => {
fetch("/uk/plpslice/listing-api/query?setId=9645&view=180&gender=Men")
.then((res) => {
return res.json();
})
.then((data) => {
setDesignerData(data.listing.products);
});
}, []);
return (
<div className="ProductFilter">
<select>
{designerData.map((designer, id) => {
return (
<option
value={[designer.brand.name]}
onChange={e => {
console.log('this is on change', e);
setSelectedDesigner(e.target.value)}}
>
{[designer.brand.name]}
</option>
);
})}
</select>
<h1>{console.log('this is the selected designer',selectedDesigner)}</h1>
</div>
);
}
export default ProductFilter;
Console.log 正在显示...
this is the selected designer null
还有一个带有虚拟数据的codesandbox
https://codesandbox.io/s/lucid-bassi-r0lrd?file=/src/Filter.js:0-875
您必须在 select 标签上调用 onchange
return (
<div className="ProductFilter">
<select onChange={(e => {
console.log('this is on change', e);
setSelectedDesigner(e.target.value)})}>
{designerData.map((designer, id) => {
return (
<option
value={[designer.brand.name]}
>
{[designer.brand.name]}
</option>
);
})}
</select>
<h1>this is the selected designer {selectedDesigner}</h1>
</div>
);
我正在构建一个过滤器以根据所选选项显示值列表。数据由获取请求填充,然后映射到显示值。
这部分工作正常。但是我发现下拉菜单似乎没有注册 onChange 事件,因此没有从 null 更新值。
这是我的代码...
import ProductCard from "../ProductCard";
import "./style.css";
function ProductFilter(props) {
const [designerData, setDesignerData] = useState([]);
const [selectedDesigner, setSelectedDesigner] = useState(null);
useEffect(() => {
fetch("/uk/plpslice/listing-api/query?setId=9645&view=180&gender=Men")
.then((res) => {
return res.json();
})
.then((data) => {
setDesignerData(data.listing.products);
});
}, []);
return (
<div className="ProductFilter">
<select>
{designerData.map((designer, id) => {
return (
<option
value={[designer.brand.name]}
onChange={e => {
console.log('this is on change', e);
setSelectedDesigner(e.target.value)}}
>
{[designer.brand.name]}
</option>
);
})}
</select>
<h1>{console.log('this is the selected designer',selectedDesigner)}</h1>
</div>
);
}
export default ProductFilter;
Console.log 正在显示...
this is the selected designer null
还有一个带有虚拟数据的codesandbox
https://codesandbox.io/s/lucid-bassi-r0lrd?file=/src/Filter.js:0-875
您必须在 select 标签上调用 onchange
return (
<div className="ProductFilter">
<select onChange={(e => {
console.log('this is on change', e);
setSelectedDesigner(e.target.value)})}>
{designerData.map((designer, id) => {
return (
<option
value={[designer.brand.name]}
>
{[designer.brand.name]}
</option>
);
})}
</select>
<h1>this is the selected designer {selectedDesigner}</h1>
</div>
);