簡體   English   中英

react 不會在輸入更改時更新功能組件狀態

[英]react is not updating functional component state on input change

當我輸入輸入並更改時,editing.hours 不會更新輸入值,但我在控制台中看到更新的值。

const nullableEntry = {
    ID: '',
    day: '',
    hours: 0.0,
    note: '',
};

const MonthTable = (props) => {
    const [editing, setEditing] = useState(nullableEntry);

    function handleHoursInput(e) {
        editing.hours = e.target.value;
        setEditing(editing);
    }

    return (
       <input type="number" value={editing.hours} step="0.01" onChange={handleHoursInput} className="form-control" name="" />
    );
};

export default MonthTable;

在 React 中,您應該避免進行狀態突變,這意味着不要顯式更改屬於現有狀態的內容。 為了讓 React 決定是否重新渲染以反映您的更改,它需要注冊一個新狀態。

養成創建狀態的克隆或深層副本的好習慣,然后對其進行更新。

嘗試這樣的事情。 在下面,我們使用擴展運算符{...}在更新狀態之前克隆狀態:

const nullableEntry = {
  ID: "",
  day: "",
  hours: 0.0,
  note: ""
};

const MonthTable = props => {
  const [editing, setEditing] = useState(nullableEntry);

  function handleHoursInput(e) {
    let newEdit = { ...editing };

    newEdit.hours = e.target.value;
    setEditing(newEdit);
  }

  return (
    <input
      type="number"
      value={editing.hours}
      step="0.01"
      onChange={handleHoursInput}
      className="form-control"
      name=""
    />
  );
};

工作沙箱: https : //codesandbox.io/s/hopeful-bogdan-lzl76

不改變狀態, editing.hours = e.target.value改變原始狀態

將您的handleHoursInput函數更改為這樣的

function handleHoursInput(e) {
    let hours = e.target.value;
    setEditing({...editing, hours});
}

在此處輸入圖片說明

您可以通過這種方式更新功能組件中的狀態

const [show, setShow] = useState(false) 
const [scopesData, setScopesData] = useState(scopes)

const submitCallBack = (data) => { 
    setShowhowAlert(true) 
    setScopesData(...scopes, scopes.push({
        id: generateKeyHash(),
        title: data.data.scopetitle,
    }))

}

這 3 行代碼正確更新狀態

  [setScopesData(...scopes, scopes.push({
    id: generateKeyHash(),
    title: data.data.scopetitle,
  })) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM