gpt4 book ai didi

reactjs - 条件函数中的功能组件设置useState

转载 作者:行者123 更新时间:2023-12-03 15:35:54 24 4
gpt4 key购买 nike

如果您在函数中设置 useState 变量,那么“if 语句”之类的条件可以吗?我读到您不应该在条件下使用钩子(Hook),但设置状态也是如此吗?示例将说明我的意思。如果我不能这样做,如果我有多个变量和条件,我该如何正确设置它。请帮帮我谢谢

我知道这一点:https://reactjs.org/docs/hooks-rules.html#explanation
但我有一些疑问

import React, { useState} from "react";

const MoreInfo = () => {

const [more_info, setMore_info] = useState("test");

const handleExpand = (event) => {
if (icon_expand === 'expand_more') {
setMore_info("test2"); // is this ok in if?
}
}

return (
<IconButton onClick={handleExpand}>
);
};

export default MoreInfo;

最佳答案

钩子(Hook)是useState .并且规则仅适用于该调用(以及可能正在使用的任何其他钩子(Hook)调用,以及自定义钩子(Hook),如 useSomething )。setState call 不是挂机调用。您正在调用从钩子(Hook)调用返回的方法。 Infact React 保证 setState渲染之间的引用不会改变。
钩子(Hook)规则:

Only Call Hooks at the Top Level

Only Call Hooks from React Functions


以下文章可能会帮助您了解这些规则存在的原因。它直观地解释了引擎盖下的钩子(Hook)。
https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e

function App() {

// THE useState CALL SHOULD BE ON TOP LEVEL
// CAN'T BE CALLED INSIDE ANY CONDITIONALS
const [myState,setMyState] = React.useState(0);

// THE setState CALLS CAN BE ANYWHERE
function changeCounter(value) {
if (value === 'increment') {
setMyState((prevState) => prevState + 1);
}
else if (value === 'decrement') {
setMyState((prevState) => prevState - 1);
}
}

return(
<React.Fragment>
<div>Counter: {myState}</div>
<button onClick={() => changeCounter('increment')}>
+
</button>
<button onClick={() => changeCounter('decrement')}>
-
</button>
</React.Fragment>
);
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

关于reactjs - 条件函数中的功能组件设置useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57806968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com