React只更新一次值



我有一个新问题:)

我有一个模态,在React Native中打开一个下拉选择,需要值。我想在模态打开时计算值。

let pickupTime; // Set a value that can be overwritten. I'm not using State because I want this value to change whenever I open the modal again.
const pickupTimeOptions = useRef([{ label: "", value: "" }]); // A ref to store the values
useEffect(() => {
const pickup_hours_today = business.pickup_hours_today; // Array of strings I pass to the modal.
console.log("pickup_hours_today", pickup_hours_today);        
const options = pickup_hours_today.map((time) => {
return {
label: time,
value: time,
};
});
pickupTimeOptions.current = options;
}, [business.pickup_hours_today]);
console.log("pickupTimeOptions", pickupTimeOptions); // Let's see if we got it

问题是ref永远不会更新。日志打印如下:

pickupTimeOptions Object {
"current": Array [
Object {
"label": "",
"value": "",
},
],
}
pickup_hours_today Array [
... // the string array of hours
]
Should be updating the ref
pickupTimeOptions Object {
"current": Array [
Object {
"label": "",
"value": "",
},
],
}
pickup_hours_today Array [
...
]
Should be updating the ref

我做错了什么?我应该换一种处理方式吗?我不介意使用状态,但是当我尝试时,每当我用下拉选择器选择不同的值时,它就会不断更新。

如果您查看控制台日志的顺序,它将解释发生了什么。

这是首先打印的,这意味着useEffect中的计算还没有发生

console.log("pickupTimeOptions", pickupTimeOptions); // Let's see if we got it

根据文档useEffect只在渲染后被调用。您需要在渲染周期之前或期间进行计算。

你可以使用在渲染过程中执行的useMemo。详细信息请参考文档

更新后的代码应该像这样

let pickupTime; // Set a value that can be overwritten. I'm not using State because I want this value to change whenever I open the modal again.
const pickupTimeOptions = useMemo(() => {
const pickup_hours_today = business.pickup_hours_today; // Array of strings I pass to the modal.
console.log("pickup_hours_today", pickup_hours_today);        
const options = pickup_hours_today.map((time) => {
return {
label: time,
value: time,
};
});
return options;
}, [business.pickup_hours_today]);
console.log("pickupTimeOptions", pickupTimeOptions); // Let's see if we got it

最新更新