在状态对象中修改 属性 的正确方法?
Right way to modify a property in a state object?
我正在使用 react 17.0.2
和 next 12.0.0
,并使用 react-date-range
(https://www.npmjs.com/package/react-date-range)
我有这3个状态
const [calendarDates, setCalendarDates] = useState(null);
const [wasCleared, setWasCleared] = useState(true);
const [focusedRange, setFocusedRange] = useState([0, 0]);
然后,当我调用组件时:
<DateRangePicker
preventSnapRefocus
showPreview
showSelectionPreview
direction="horizontal"
focusedRange={focusedRange}
minDate={new Date()}
monthDisplayFormat="MMMM yyyy"
months={2}
ranges={calendarConfig.calendarDates}
showDateDisplay={false}
showMonthAndYearPickers={false}
weekdayDisplayFormat="EEEEEE"
onChange={item => handleDatesChange([item.selection])}
onRangeFocusChange={setFocusedRange} // this is the line what i dont understand
/>
我只想更改这 3 个状态,其中一个具有 3 个属性,就像:
const [calendarConfig, setCalendarConfig] = useState({
focusedRange: [0, 0],
wasCleared: true,
calendarDates: null
});
现在,我想改变这一行
onRangeFocusChange={setFocusedRange}
为此
onRangeFocusChange={item => handleFocusedRange(item)}
那么,我做:
const handleFocusChange = item => {
setCalendarConfig({
...calendarConfig,
focusedRange: item,
});
};
但不起作用。
我的问题是,到底在做什么? onRangeFocusChange={setFocusedRange}
以及我如何替换它,以更改 calendarConfig.focusedRange
所有接缝对我来说都很好,除了设置状态:
const handleFocusChange = item => {
setCalendarConfig((prevConfig) => {
prevConfig.focusedRange = item;
return prevConfig;
});
};
我正在使用 react 17.0.2
和 next 12.0.0
,并使用 react-date-range
(https://www.npmjs.com/package/react-date-range)
我有这3个状态
const [calendarDates, setCalendarDates] = useState(null);
const [wasCleared, setWasCleared] = useState(true);
const [focusedRange, setFocusedRange] = useState([0, 0]);
然后,当我调用组件时:
<DateRangePicker
preventSnapRefocus
showPreview
showSelectionPreview
direction="horizontal"
focusedRange={focusedRange}
minDate={new Date()}
monthDisplayFormat="MMMM yyyy"
months={2}
ranges={calendarConfig.calendarDates}
showDateDisplay={false}
showMonthAndYearPickers={false}
weekdayDisplayFormat="EEEEEE"
onChange={item => handleDatesChange([item.selection])}
onRangeFocusChange={setFocusedRange} // this is the line what i dont understand
/>
我只想更改这 3 个状态,其中一个具有 3 个属性,就像:
const [calendarConfig, setCalendarConfig] = useState({
focusedRange: [0, 0],
wasCleared: true,
calendarDates: null
});
现在,我想改变这一行
onRangeFocusChange={setFocusedRange}
为此
onRangeFocusChange={item => handleFocusedRange(item)}
那么,我做:
const handleFocusChange = item => {
setCalendarConfig({
...calendarConfig,
focusedRange: item,
});
};
但不起作用。
我的问题是,到底在做什么? onRangeFocusChange={setFocusedRange}
以及我如何替换它,以更改 calendarConfig.focusedRange
所有接缝对我来说都很好,除了设置状态:
const handleFocusChange = item => {
setCalendarConfig((prevConfig) => {
prevConfig.focusedRange = item;
return prevConfig;
});
};