【发布时间】:2021-09-07 15:52:21
【问题描述】:
我正在尝试制作一个简单的(可能)反应计算器,增加的运输成本取决于距离。但我现在真的很累。
假设汽车每次从市中心到郊区都会骑。汽车将从起点取一个包裹并将其运送到终点。离市区越远,每1英里/公里的价格越高。
我的变量:x:起点,y:终点,n:每 1 英里的成本\km(n = 1,2,3 只是为了更好的解释,所以 n+1 在这里不起作用,稍后我想将其更改为 .24 cents\points 或其他)
预期结果:
示例:如果 x = 10, y = 25 那么成本 = 30 $ \ points \ 不管 (5 + 10 + 15 => 因为介于 (
5 和 15) n = 1,介于 (
15 和 20) n = 2 和之间 (
20 和 25)n = 3 ..如果我们要走更长的距离,依此类推)
实际结果:取决于
第一个例子:取决于更高的价格(n),所以玩家将被收取费用......就像他从更高、最有价值的距离开始(如果 x = 10,y = 25 那么成本 = 45,因为n 在 20 和 25 之间 = 3)
第二个例子:取决于较低的价格(x = 10,y = 25 => 成本 = 15)
可能我错过了一些反应或一些数学逻辑,但无法意识到我到底需要做什么,我在我的宠物项目的这一部分上浪费了很多时间,所以我第一次'我寻求帮助 :) 感谢您的提前!
我也不明白为什么有时需要点击两次按钮来更新useState..
我的代码沙箱给你https://codesandbox.io/s/distance-react-calc-on-states-rjuek
如果你想在这里查看代码:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [x, setX] = useState(5);
const [y, setY] = useState(10);
const [n, setN] = useState(null); // n - the cost value per 1 mile/km
const [total, setTotal] = useState((y - x) * n);
function calculateTotal() {
if (x <= 5 && y < 15) {
setN(1);
setTotal((y - x) * n);
} else if (x <= 15 && y < 20) {
setN(2);
setTotal((y - x) * n);
} else if (x <= 20 && y <= 25) {
setN(3);
setTotal((y - x) * n);
} else if (x <= 25 && y < 30) {
setN(4);
setTotal((y - x) * n);
} else if (30 <= x && y < 35) {
setN(5);
setTotal((y - x) * n);
} else if (35 <= x && y < 40) {
setN(6);
setTotal((y - x) * n);
}
return calculateTotal;
}
return (
<div className="Calc">
<div className="number-inputs">
<input
type="number"
step="1"
value={x}
onChange={(e) => setX(+e.target.value)}
/>
<input
type="number"
step="1"
value={y}
onChange={(e) => setY(+e.target.value)}
/>
</div>
<button onClick={calculateTotal}>Calc</button>
<h2 id="currentDistance">{total}</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
【问题讨论】:
-
return calculateTotal;可能不是您的意思。你也不需要n的状态(这就是为什么更改不会立即可见)
标签: javascript reactjs react-hooks calculator distance