【问题标题】:react is not updating functional component state on input changereact 没有在输入更改时更新功能组件状态
【发布时间】:2019-12-29 08:11:20
【问题描述】:

当我输入输入并更改时,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;

【问题讨论】:

  • 不要改变状态!!!

标签: javascript reactjs functional-programming state


【解决方案1】:

在 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

【讨论】:

    【解决方案2】:

    不要改变状态,editing.hours = e.target.value 改变原始状态

    将您的 handleHoursInput 函数更改为类似的内容

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

    【讨论】:

      【解决方案3】:

      您可以通过这种方式更新功能组件中的状态

      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,
        })) 
      

      【讨论】:

        猜你喜欢
        • 2021-03-19
        • 2016-09-23
        • 2020-08-12
        • 2018-09-21
        • 2020-05-12
        • 2021-11-02
        • 2021-07-21
        • 2021-10-07
        • 1970-01-01
        相关资源
        最近更新 更多