我是React的新手,也是React Hooks的新手。我想为用户输入和另一个数组(这里是代码的最后一块(提供react钩子,当用户输入更改时,它会自动更新。我试着跟上去,但我想我走错了路。有人知道我该怎么办吗?
// 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)
}
]);
首先,初始化要更新的状态,在您的情况下,它似乎是const [totalInputRates, setTotalInputRates] = useState([])
然后你可以使用useEffect挂钩,就像一样
useEffect(() => {
setTotalInputRates(your values)
}, [hurdleRatesBC, maturitiesMarkups1, ratingMarkups])
依赖数组是放置状态的位置。如果这些变量发生变化,就会触发useEffect钩子,因此setTotalInputRates
也会被触发。
你可以在这里阅读更多关于使用效果
希望这能有所帮助。