[英]Using nested hooks to update state
I'm trying to figure out how I can use nested hooks to update state in my parent component. 我试图弄清楚如何使用嵌套的钩子来更新父组件中的状态。 I recently learned that hooks basically follow the same setState() async updating pattern but I'm struggling to find my war around that.
我最近了解到,钩子基本上遵循相同的setState()异步更新模式,但是我正在努力寻找解决方法。
I have 3 custom hooks: 我有3个自定义钩子:
useValidateContent
: A custom hook to validate a specific form. useValidateContent
:用于验证特定表单的自定义钩子。
useValidateRuleOne
: A custom hook to validate a specific rule. useValidateRuleOne
:用于验证特定规则的自定义钩子。
useValidateRuleTwo
: A custom hook to validate another specific rule. useValidateRuleTwo
:用于验证另一个特定规则的自定义钩子。
I want to use useValidateRuleOne
and useValidateRuleTwo
in useValidateContent
and update the ParentComp on click. 我想用
useValidateRuleOne
和useValidateRuleTwo
在useValidateContent
和更新点击ParentComp。 Right now it take 2 click for the messages to appear. 现在,需要两下单击才能显示消息。
What is the proper way to use nested custom hooks so that state updates on first on first run. 使用嵌套的自定义挂钩的正确方法是什么,以便在首次运行时首先更新状态。
const { useState } = React; const useValidateRuleOne = initState => { const[valid, setValid] = useState(initState) const[errorMsg, setErrorMsg] = useState(null) const validate = () => { // For test purposes just set to false setValid(false) setErrorMsg('There was an error validating rule one') } return [valid, validate, errorMsg] } const useValidateRuleTwo = initState => { const[valid, setValid] = useState(initState) const[errorMsg, setErrorMsg] = useState(null) const validate = () => { // For test purposes just set to false setValid(false) setErrorMsg('There was an error validating rule two') } return [valid, validate, errorMsg] } const useValidateContent = initState => { const [valid, setValid] = useState(initState); const [validOne, validateOne, errorOne ] = useValidateRuleOne(true) const [validTwo, validateTwo, errorTwo ] = useValidateRuleTwo(true) const [errorMsg, setErrorMsg] = useState(""); const validate = () => { validateOne() validateTwo() let errorMsg = ''; if (!validOne) errorMsg += errorOne; if (!validTwo) errorMsg += errorTwo; setErrorMsg(errorMsg) if (errorMsg.length > 1) setValid(false) } return [valid, validate, errorMsg]; }; function ParentComp() { const [contentIsValid, validate, contentError] = useValidateContent(true); const initValidate = () => { // values before running validate validate(); }; return ( <div> <button onClick={initValidate}>initValidate</button> contentIsValid: {contentIsValid.toString()}, contentError: {contentError} </div> ); } ReactDOM.render(<ParentComp />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>
According to Hooks API, you shouldn't call a hook conditionally or inside nested functions. 根据Hooks API,您不应有条件地或在嵌套函数内部调用一个钩子。 https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
One solution for your issue is to add useEffect, which will fire any time your specified dependencies change. 解决此问题的一种方法是添加useEffect,它会在您指定的依赖项发生更改时触发。 Here's a working example: https://codesandbox.io/s/5zyljjm7o4
这是一个工作示例: https : //codesandbox.io/s/5zyljjm7o4
Make pure functions from validation rules and store state only on one place. 根据验证规则制作纯函数,并将状态仅存储在一个地方。 It should be cleaner and also better for testing.
它应该更清洁,也更适合测试。 https://codesandbox.io/s/r4v026lxno
https://codesandbox.io/s/r4v026lxno
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.