我是React的新手,正在使用React Hooks。我想为用户输入和另一个数组(这里是代码的最后一块)提供反应挂钩,该数组在用户输入更改时会自动更新。我尝试关注,但我想错了方向。有人知道我该如何处理吗?
// User Inputs
const [hurdleRatesBC, sethurdleRatesBC] = useState({
bcLombard: initialValue.bcLombard
});
const [maturitiesMarkups1, setmaturitiesMarkups1] = useState({
onSightMarkup: initialValue.onSightMarkup
});
const [ratingMarkups, setratingMarkups] = useState({
ratingAMarkup: initialValue.ratingAMarkup
});
// Destructuring
const { bcLombard: bcl } = hurdleRatesBC;
const {
ratingAMarkup: ra,
ratingBMarkup: rb,
ratingCMarkup: rc
} = ratingMarkups;
const {
onSightMarkup: m11,
lt1mMarkup: m12,
oneTo12mMarkup: m13,
oneTo5yMarkup: m14,
gt5yMarkup: m15
} = maturitiesMarkups1;
// Should be updated automatically when changing Userinput
const [totalInputRates, settotalInputRates] = useState([
{
name: "On Sight",
product: "bcl",
"Rating C": roundSum(bcl, m11, rc),
"Rating B": roundSum(bcl, m11, rb),
"Rating A": roundSum(bcl, m11, ra)
}
]);
答案 0 :(得分:2)
首先,初始化要更新的状态,在您的情况下,该状态似乎为const [totalInputRates, setTotalInputRates] = useState([])
然后您可以使用useEffect挂钩,就像这样
useEffect(() => {
setTotalInputRates(your values)
}, [hurdleRatesBC, maturitiesMarkups1, ratingMarkups])
依赖数组是放置状态的地方。如果这些变量发生更改,则会触发useEffect挂钩,因此您的setTotalInputRates
也是如此。
You can read more about the useEffect here
希望这会有所帮助。