"Set" React Hooks 中的方法不起作用



我试图设置一个包含当前年份及其前4年的状态,但由于某些原因,我无法正确设置状态。

const [years, setYears] = useState({ selected: 0, availables: [] })
const getYears = () => {
const y = {
selected: new Date().getFullYear(),
availables: [],
}
for (var i = 0; i < 5; i++) {
y.availables.push(y.selected - i)
}
setYears(y)
}
useEffect(() => {
getYears()
}, [])

最后;年";状态保持其初始值({selected: 0, availables: []}(。

有人能帮我找出我做错了什么吗?

您可以通过将状态分为selectedYear(数字(和availableYears(数组(来简化逻辑。但是,如果您打算将它们包含在一个对象中,那么请查看下面的示例。单击运行代码片段按钮查看工作示例。

// current year
const currentYear = new Date().getFullYear();
// creates an array of available years where "num" represents 
// the amount to create/subtract from "year"
const createAvailableYears = (num, year) => [
...Array(num)
.fill()
.map((_, key) => year - key - 1)
];
function App() {
const [years, setYears] = React.useState({
selected: currentYear,
available: createAvailableYears(4, currentYear)
});
const handleChange = React.useCallback(({ target: { value } }) => {
setYears({
// updates the selected year
selected: value,
// sets the available years to: [selected year - 4 years]
available: createAvailableYears(4, value)
});
}, []);
return (
<div className="app">
<select className="select" onChange={handleChange} value={years.selected}>
{createAvailableYears(10, 2021).map(year => (
<option key={year} value={year}>
{year}
</option>
))}
</select>
<h1>Selected year: {years.selected}</h1>
<h3>Available years: {years.available.join(", ")}</h3>
</div>
);
}
// Render it
ReactDOM.render(
<App />,
document.getElementById("react")
);
.app {
font-family: sans-serif;
text-align: center;
}
.select {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

const [years, setYears] = useState({ selected: 0, availables: [] });
const getYears = () => {
const tempSelected = new Date().getFullYear();
let tempAvailables = [];
for (var i = 0; i < 5; i++) {
tempAvailables.push(tempSelected - i);
}
setYears({ selected: tempSelected, availables: tempAvailables });
};
useEffect(() => {
getYears();
}, []);

相关内容

  • 没有找到相关文章

最新更新