【问题标题】:Input fields "inherits" value from past input fields when changing state更改状态时,输入字段“继承”过去输入字段的值
【发布时间】:2021-08-09 05:23:41
【问题描述】:

我有一个简单的组件,它有一个标题和两个输入字段

<h2>Login</h2>
<input type='text' id="login-username" placeholder="Username"></input>
<input type='password' id="login-password" placeholder="Password"></input>
<button className="btn btn-success" id="login-button">Login</button>

然后我有一个删除和输入字段(密码)并添加另一个的状态

<h2>Login</h2>
<input type='text' id="login-username" placeholder="Username"></input>
<input type='password' id="login-code" placeholder="Code"></input>
<button className="btn btn-success" id="login-button">Login</button>
import '../css/Login.css';

import GenericWindow from "../components/GenericWindow";
import React, { useEffect, useRef } from "react";
import { store } from 'react-notifications-component';


class Login extends React.Component{
    constructor(props){
        super(props);
        document.title = "Login"
        this.state = {
            view:'login'
        }
    }

    render(){
        if (this.state.view == "login"){

            return(
                <GenericWindow>
                <h2>Login</h2>
               <input type='text' id="login-username" placeholder="Username"></input>
               <input type='password' id="login-password" placeholder="Password"></input>
               <a onClick={
                            () => {
                                this.setState({view:"login-code"})
                            }
                        }>Login with code</a>
               <button className="btn btn-success" id="login-button">Login</button>

            </GenericWindow>
        )
        }else{
            return(
                    <h2>Login</h2>
                    <input type='text' id="login-username" placeholder="Username"></input>
                    <input type='password' id="login-code" placeholder="Code"></input>
                    
                    <button className="btn btn-success" id="login-button">Login</button>
                    </GenericWindow>
                )
        }
    }
}


export default Login;

我使用 this.SetState 更改状态,问题是当我将状态从第一个更改为第二个时,如果密码字段有任何内容,则当我更改状态时代码字段具有它。我目前正在学习 reactjs,所以我可能完全错了,状态不是要走的路。无论如何,我怎样才能防止这种行为?或者如果我不应该为此使用状态,我应该使用什么?

【问题讨论】:

  • 如果您不显示代码,我们将无法发现错误。

标签: javascript reactjs


【解决方案1】:

这是React's reconciliation algorithm 的预期行为。虽然您认为它是删除一个输入并添加另一个输入,但 React 看到的是仍然有一个输入字段,只是更改了 idplaceholder 属性。它不会卸载元素并安装一个新元素 - 它只是道具的变化。这反映在 DOM 中 - React 保持 相同 输入元素并且只更改其属性值。

为避免这种情况,您可以给他们不同的keys。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多