如何创建一个新的状态对象而不是对现有状态对象进行突变?

时间:2020-05-14 01:43:32

标签: reactjs react-hooks

嗨,我有一个状态

select employeeID, shiftDate
from (
    select 
        oc.*,
        lead(startDT)   over(partition by employeeID, shiftDate order by rowID) leadStartDT,
        lead(paycodeID) over(partition by employeeID, shiftDate order by rowID) leadPaycodeID,
        lag(endDT)      over(partition by employeeID, shiftDate order by rowID) lagEndDT,
        lag(paycodeID)  over(partition by employeeID, shiftDate order by rowID) lagPaycodeID
    from #onCallTable oc
) t
where 
    paycodeID = 'OC'
    and lagPaycodeID = 'CB' 
    and leadPaycodeID = 'CB'
    and lagEndDT = startDT
    and leadStartDT = endDT

在onClick上,我称之为const [value, setValue] = useState({}) const handleClick = () => { let newObject = { 'name':'ironman'} setValue(newObject); } 函数。并使用newObject更新状态值。我在改变状态吗?或如何在不更改现有对象的情况下创建newState对象?任何帮助或建议,不胜感激。提前致谢。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您将通过以下方式生成新状态

value.name = 'ironman';
setValue(value);

这就是创建一个新状态对象 并对其进行突变的意思。这样的代码是在改变状态,而相关代码不是。

要创建newState对象而不更改现有对象,只需克隆它即可。对于深层对象树而言,这可能很棘手。对于包含一个级别属性的简单对象(我通常设计这样的状态),只是

const newState = {...value, {prop: newValue}};
setValue(newState)

https://reactjs.org/docs/hooks-state.html#tip-using-multiple-state-variables之后,最好为不同的属性定义多个状态变量。