为什么ReactJs表单的输入已预先加载有载值,所以不允许对其进行更新

问题描述 投票:0回答:2

我正在使用一种表格,该表格应允许用户更新已经保存的数据的内容。稍后,我将输入的现有数据加载到表单输入中,如下所示:-

  <input value={profile.displayName} 
  name="displayName" type="text" 
  placeholder="Display Name" 
  /> // it dosn't work  So I tried next

  <input value={profile.displayName} 
  name="displayName" type="text" 
  placeholder="Display Name" 
  onChange={(e) => {setDisplayName(e.target.value )}}/> // Same issue

因此,如何加载现有数据,并且数据必须在from中可编辑?

更多澄清代码:-我正在使用这样的钩子:-

const [profile, setProfile] = useState({});

useEffect(() => {

if (props.match.params.title) {
  setTitle(props.match.params.title);
} else if (props.location.state.title) {
  setTitle(props.location.state.title);
}

if (props.location.state) {
  if (props.location.state.profile) {
    setProfile(props.location.state.profile)
    console.warn("profile: ", props.location.state.profile)
  }
}

}

因此,配置文件作为道具来自另一个组件。这部分很好。也可以将数据加载到表单中。但是在加载数据后,我无法对其进行编辑。

reactjs forms preload
2个回答
0
投票

您将初始配置文件设置为空对象,但将输入的默认值分配为profile.displayName,即undefined,反应将引发以下警告。

警告:组件正在更改要控制的文本类型的不受控制的输入。输入元素不应从不受控制切换为受控制(反之亦然)。确定在组件的使用寿命中使用受控或不受控制的输入元素。*

您的初始对象应该像

const [profile, setProfile] = useState({
  displayName: ""
});

然后更新值,如

<input
  value={profile.displayName}
  name="displayName"
  type="text"
  onChange={e => {
    setProfile({ ...profile, displayName: e.target.value });
  }}
/>

// Get a hook function
const {useState, useEffect} = React;

function App() {
  const [profile, setProfile] = useState({
    displayName: ""
  });

  useEffect(() => {
    setProfile({
      displayName: "StackOverflow"
    });
  }, []);

  return (
    <div>
      <input
        value={profile.displayName}
        name="displayName"
        type="text"
        onChange={e => {
          setProfile({ ...profile, displayName: e.target.value });
        }}
      />
      <p>{profile.displayName}</p>
    </div>
  );
}
// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

0
投票

假设您有一个新的钩子

const [displayName,setDisplayName] = useState('');

设置配置文件时在使用效果中,还要设置显示名称。

SetDisplayName(profile.displayName)

最后输入中

    <input value={displayName} name="displayName" type="text" placeholder="Display Name" onChange={(e) => {setDisplayName(e.target.value )}}/>
© www.soinside.com 2019 - 2024. All rights reserved.