如何改变状态在钩子从外部函数在反应?



我必须在一个项目中做一些改变,我不太熟悉react。如何从外部函数更改钩子的状态?这是我的:

export const HomeView = () => {
[...]
const ProductDetails = () => {
const [number, setNumber] = React.useState(0);
const [currentPrice, setCurrentPrice] = React.useState(5);
React.useEffect(() => {
const fetchData = async () => {

// get available items and current price when page loads
[...]
const number = 15;
setNumber(number);
[...]
const currentPrice = 10;
setCurrentPrice(currentPrice);

};
fetchData();
}, []);
// returns available items and current price with a button to buy
return (
<div >
<h2>Current price : {currentPrice} </h2>
<button onClick={() => buyProduct({currentPrice})}>
"Click me"
</button>
<h2>Available {number} / 10000</h2>
</div>
);

const buyProduct = async ({currentPrice}: {currentPrice: number;}) => {
//users buys product, refresh available number
[...]
const number = 14;
//each time a buy occurs, i have to increase price
const currentPrice = 11;
//How do i pass this new data to update the data in ProductDetails when a buy occurs without 
//refreshing the whole page from the browser?
};
return (
<div >
[...]
<ProductDetails />
[...]
</div>
);

我想过将钩子从ProductDetails中移动到整个HomeView中,但我真的不知道整个过程是如何工作的,因为我不熟悉react。提前感谢您的帮助。

我认为不建议这样做。https://reactjs.org/docs/hooks-rules.html only-call-hooks-from-react-functions

只调用React函数中的钩子不要从常规JavaScript函数中调用Hooks。相反,您可以:

  • 从React函数组件调用钩子。
  • 从自定义钩子调用钩子

通过遵循此规则,您可以确保组件中的所有有状态逻辑在其源代码中清晰可见。

然而,你可以传递一个内部函数作为参数,它将更新状态到方法buyProduct,它将更新状态号和currentPrice使用setNumber &setCurrentPrice,并在buyProduct本身中调用。