为什么状态更改后此功能React组件会重新呈现?

时间:2020-06-22 13:52:59

标签: reactjs react-functional-component

我有以下代码...

const Thing = ({...})=> {
    const initialState = {
        foo: ''
    }
    const [state, setState] = useState(initialState);
    const changeFormvalue = (e) => {
        state.foo = e.target.value;
        setState(state);
    }
    return (
        <input type="text" name ="foo"
               value={state.foo}
               onChange={changeFormvalue} />
    )
}

运行时,我看到它命中了功能,并且看到它设置了值。但是,在setState命令之后,页面不会重新呈现,并且值也不会更新。

为什么页面没有更新?

1 个答案:

答案 0 :(得分:0)

正确设置状态(不更改状态)。

请参见下面的重构代码,并进一步阅读问题注释中提供的链接。

const Thing = ({...})=> {
    const initialState = {
        foo: ''
    }
    const [state, setState] = useState(initialState);
    const changeFormvalue = (e) => {
        const value = e.target.value;
        setState(prev => ({...prev, foo: value, assetName: value}));
    }
    return (
        <input type="text" name ="foo"
               value={state.foo}
               onChange={changeFormvalue} />
    )
}