【发布时间】:2021-10-29 13:35:41
【问题描述】:
我有一个反应功能组件。我有一个称为当前属性的状态。
const [currentProperty, setCurrentProperty] = useState({})
我正在尝试使用 setCurrentProperty 分配一个对象,但它不起作用,统计数据保持为黑色对象。这是当前代码:
function handleEditingMortagePaymentOpen(id){
setCurrentlyEditingMortgagePayments(true)
setSelectedPropertyById(id)
for(let i = 0; i < properties.length; i++){
if(properties[i]['id'] == id){
console.log(properties[i])
setCurrentProperty(properties[i])
console.log(currentProperty)
}
}
}
这是 console.log 显示的内容
{id: 3, picture: '../images/unnamed.jpeg', price: 464000, status: 'Active', beds: 3, …}
address: "Plan 2 Plan, Neo at Mission Foothils"
agent: "John Doe"
baths: 3
beds: 3
broker: "JD Realty"
days_listed: 29
hoa: 12
home_insurance: 239
id: 3
living_space: 3964
mls: "OC3628342"
picture: "../images/unnamed.jpeg"
price: 464000
property_tax: 68
rent: 2200
sqft: 1939
status: "Active"
[[Prototype]]: Object
{}
【问题讨论】:
-
您希望 console.log 反映更改,但这不是反应状态更新的工作方式。我建议您阅读如何在 react 中触发状态更新
-
使用循环来不断设置状态并不是一个好主意。
-
是的,虽然这段代码等同于
arr.find(item); setCurrentProperty(item),因为它唯一的匹配是我认为是唯一标识符的id。问题是设置状态行为是异步与同步。这是一个关于 SO 的常见问题。
标签: javascript reactjs