Reactjs react状态映射即使在更新状态后也不显示数据-react js
这是主要代码:Reactjs react状态映射即使在更新状态后也不显示数据-react js,reactjs,Reactjs,这是主要代码: const [selectedProductList, setSelectedProductList] = useState([]); const handleProductSelection = (event) => { const { name, value, label } = event; setSelectedProductList((selectedProductList) => [ ...selectedProductL
const [selectedProductList, setSelectedProductList] = useState([]);
const handleProductSelection = (event) => {
const { name, value, label } = event;
setSelectedProductList((selectedProductList) => [
...selectedProductList,
{
product_id: value,
quantity: "",
unit_id: "",
price_per_unit: "",
},
]);
};
useEffect(() => {
console.log("selectedProductList >>", selectedProductList);
}, [selectedProductList]);
return (
<>
//This select is just using the react select and its triggering handleProductSelection onChange
<Select
id="product_id"
name="product_id"
onChange={handleProductSelection}
value={products.filter(function (option) {
return option.value === formData.product_id;
})}
options={products}
className={` ${
errors["product_id"] ? "is-invalid" : ""
}`}
/>
//THIS IS THE MAIN POINT OF ISSUE
//THIS ONE IS NOT DISPLAYING
{selectedProductList.map((prod) => {
prod && (
<div>
DUMMY <span>{prod.product_id}</span>
</div>
);
})}
</>
)
const[selectedProductList,setSelectedProductList]=useState([]);
常量handleProductSelection=(事件)=>{
常量{name,value,label}=event;
setSelectedProductList((selectedProductList)=>[
…所选产品列表,
{
产品标识:价值,
数量:“,
单位编号:“,
每单位价格:“,
},
]);
};
useffect(()=>{
log(“selectedProductList>>”,selectedProductList);
},[selectedProductList]);
返回(
//此选择仅使用react select及其触发手柄ProductSelection onChange
//这是主要问题
//这个没有显示
{selectedProductList.map((prod)=>{
生产和(
虚拟{prod.product_id}
);
})}
)
但是,这个方法确实有效:
//THIS ONE IS CONSOLING ON EVERY CHANGE
{selectedProductList.map((prod) => {
prod && <div>{console.log(`hit here`)}</div>;
})}
//每一次变化都会让这个人感到安慰
{selectedProductList.map((prod)=>{
prod&{console.log(`hit here`)};
})}
这里出了什么问题。我已经对代码本身添加了必要的注释
我还检查了
useffect
,它正在正确更新状态,我可以通过查看useffect中的控制台来验证。您需要添加返回值
:
{selectedProductList.map((prod) => {
return prod && (
<div>
DUMMY <span>{prod.product_id}</span>
</div>
);
})}
请记住,prod&
不会避免渲染prod
错误的元素。它将呈现一些您可能不需要的内容,比如false
。在映射之前,您应该考虑使用<代码>数组.Studio.Studio删除错误的条目:
{selectedProductList.filter(Boolean).map((prod) =>
<div>
DUMMY <span>{prod.product_id}</span>
</div>
)}
{selectedProductList.filter(布尔).map((prod)=>
虚拟{prod.product_id}
)}
希望这有帮助
{selectedProductList.filter(Boolean).map((prod) =>
<div>
DUMMY <span>{prod.product_id}</span>
</div>
)}