【问题标题】:How do I make error message dissapear when user move to another page in React?当用户移动到 React 中的另一个页面时,如何使错误消息消失?
【发布时间】:2021-09-24 02:32:03
【问题描述】:

假设我有这个登录表单

<form>
      <label>
        <p>Username</p>
        <input type="text" />
      </label>
      <label>
        <p>Password</p>
        <input type="password" />
      </label>
      <div>
        <button type="submit">Submit</button>
      </div>
      <div>
        <span>{errMsg}</span>
      </div>
    </form>

with errMsg 来自 useState 钩子,当用户登录失败时该钩子将被更改。当用户移动到另一个页面然后返回时,如何使 errMsg 的状态恢复为空或“”? useEffect 在这里不起作用,因为当 errMsg 更新时,它会重新渲染组件并使 errMsg 为空。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    在这个组件中包含一个状态。当出现错误时,状态将为真。如果没有错误状态将是错误的。最初它将是错误的。当用户返回此页面时,组件将重新渲染,状态将为 false。

    const [isError, setIsError] = useState(false);
    
    //if error then set isError to true
    
    //in UI check this
    <div>
        <span>{isError ? errMsg : ""}</span>
    </div>
    

    或者,如果您使用父组件中的状态,则尝试使用“useEffect”挂钩复制“componentWillUnmount”生命周期的功能。当组件被卸载(用户转到另一个页面)时,状态将设置为 false。

    【讨论】:

    • 我用它来复制 componentWillUnmount 生命周期 ``` useEffect(() => { return () => { //将错误消息设置为 "" } }, []) ```
    • 在useEffect的return内部,设置isError状态值为false。
    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多