简体   繁体   English

反应状态不更新 UI

[英]react state is not updating the UI

I have a Form Component where it contains a state that should be updated (on input change) and it looks like this:我有一个表单组件,它包含一个应该更新的状态(在输入更改时),它看起来像这样:

import { useState } from 'react';

export const Test = () => {
const [state, setState] = useState({
    name: 'khaled',
    age: 18
})

const handleInputChange = (e) => {
    let stateCopy = state 

    for(let key in stateCopy) {
        if(key === 'name') {
            stateCopy[key] = e.target.value;
        }
    }

    setState(stateCopy);
}


return(
    <div>
        <span>Name</span>
        <input onChange={ handleInputChange } />
        <span>{state.name}</span>
    </div>
)
}

and it imported in the app component并将其导入到应用程序组件中

import { Test } from '../../components/Test';

function App() {
  return (
    <Test />
  );
}

export default App;

and whenever i try to change the name inout it not update the ui每当我尝试更改名称 inout 时,它都不会更新 ui

To make the input a controlled component, both value and onChange props should be assigned.要使输入成为受控组件,应分配valueonChange道具。

<input value={state.name} onChange={handleInputChange} />

handleInputChange function can be improved to make sure that the state is updated immutably:可以改进handleInputChange函数以确保状态更新不变:

const handleInputChange = ({ target: { value } }) => {
    setState(prevState => ({...prevState, name: value}));
}

This does not work because your "stateCopy" object isn't actually a copy, its the actual state object.这不起作用,因为您的“stateCopy”对象实际上不是副本,而是实际的状态对象。 you are setting the state to the same object which causes react to think the state didn't change at all.您将状态设置为相同的对象,这会导致反应认为状态根本没有改变。

instead you should copy the state like this相反,您应该像这样复制状态

const handleInputChange = (e) => {
    let stateCopy = {...state}
    state.name = e.target.value

    setState(stateCopy);
}

You should also note that unless there is a good reason for your choice of state in my opinion you should use a seperate useState for each element in the state which results in the much simpler您还应该注意,除非我认为您选择状态有充分的理由,否则您应该为状态中的每个元素使用单独的 useState ,这会导致更简单的

import { useState } from 'react';

export const Test = () => {
const [name, setName] = useState('khalad')
const [age, setAge] = useState(18)

const handleInputChange = (e) => {
    setName(e.target.value)
}

return(
    <div>
        <span>Name</span>
        <input onChange={ handleInputChange } />
        <span>{state.name}</span>
    </div>
)
}

simply do it like this, it will work简单地这样做,它会起作用

const handleInputChange = (e) => {
       
setState({...state, name: e.target.value})
        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM