【发布时间】:2021-07-11 05:14:48
【问题描述】:
我是 react 新手,需要帮助才能使用 UseState 实现价格计数器。 我想要做的而不是下面的代码是将价格用作 useState 而不是像“const [price, setPrice] = useState(995)”
取决于有多少员工,价格将提高 220。
有人可以帮我吗?
import React, {useState} from 'react';
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';
import './App.css';
function App() {
const [employees, setEmployees] = useState(1)
let price = 0;
const calculatePrice = () => {
if (employees <= 4 && price !== 995) {
return price = 995;
} else if (employees >= 5 && employees <= 50) {
return price = employees * 220;
} else if (employees >= 51 && employees <= 100) {
return price = 995 + employees * 200;
} else if (employees >= 101 && employees <= 200) {
return price = 995 + employees * 195;
} else if (employees >= 201) {
return price = "Kontakta oss för offert!";
}
return 345;
}
return (
<div className="App">
<div className="calculator">
<div>Pris: {calculatePrice()}</div>
<div> Antal anställda: {employees}</div>
{/* <div> anställd{employees !== 1 && 'a'} {employees}</div> */}
<Slider
min={1}
max={201}
value={employees}
onChange={(v) => setEmployees(v)}
/>
</div>
</div>
);
}
export default App;
【问题讨论】:
-
price似乎是您的employees状态值的派生值。您通常不会将值存储在易于从状态派生的状态中。 -
你的代码现在有什么问题?它似乎有效,为什么需要
useState来存储价格? -
我认为它更干净。我也想学习怎么做:)
-
它不是很干净,如果价格与员工有关,那么在你的组件中计算价格是完全有效的,我认为它比使用状态变量更好,因为价格永远不会由用户手动