React Hooks-将状态设置为初始状态



我正在使用React useState创建一个处于状态的对象。在成功调用API之后,这将更新为数据对象。

我有一个可以更改此状态的表单,但我也有一个取消按钮。单击取消时,如何将此状态恢复为其初始值(在API调用之后(?

我应该创建另一个状态变量并将初始状态存储在那里,然后在此基础上更新我的状态吗?

const [basePosition, setBasePosition] = useState({});
const [position, setPosition] = useState({
id: '',
title: '',
description: '',
authoredBy: '',
createdDate: '',
lastUpdatedBy: '',
lastUpdateDate: '',
sliderResponses: [],
tileResponses: [{}],
template: {}
});```
const initialState = {
id: '',
title: '',
};
const Test = () => {
const [position, setPosition] = useState(initialState);
return <>
...form
<button onClick={() => setPosition(initialState)}>Reset</button>
</>;
};

不要创建另一个状态变量来存储初始状态,因为它会导致另一个重新渲染,而是在安装组件时初始化初始状态对象:

let initialState = null;
React.useEffect(() => {
initialState = position;
},[])

当你想重置到初始状态时,只需使用:

setPosition(initialState);

您不需要创建另一个状态。只需声明一个不会更改的初始状态,并在需要重置时将其分配到位置状态。例如:

import React,{useState} from 'react'
const YourComponent = () =>{
const initialState = {
id: '',
title: '',
description: '',
authoredBy: '',
createdDate: '',
lastUpdatedBy: '',
lastUpdateDate: '',
sliderResponses: [],
tileResponses: [{}],
template: {}
}
const [basePosition, setBasePosition] = useState({});
const [position, setPosition] = useState(initialState);
const resetState = () =>{
setPosition(initialState)
}
}

对于是否应该存储初始值的问题,答案是Yes。

这将是维护代码的最简单方法。所以把你的初始值放在一个常数中:

const INITIAL_VALUES = {
id: '',
title: '',
description: '',
authoredBy: '',
createdDate: '',
lastUpdatedBy: '',
lastUpdateDate: '',
sliderResponses: [],
tileResponses: [{}],
template: {}
}

每次你想使用初始对象时,只需将其展开,一切都很好(展开以丢失对常量的引用(:

const [basePosition, setBasePosition] = useState({});
const [position, setPosition] = useState({...INITIAL_VALUES});

稍后重置时:

setPosition({...INITIAL_VALUES})

import React, { useState } from 'react'
// counter 
function Example3() {
const [initial, setIncrement] = useState(0)

const increment = () => {
setIncrement(initial + 1)
}
const dincrement = () => {
setIncrement(initial - 1)
}

const reset = () => {
setIncrement(0)
}


return (

<div>
<p>{initial}</p>
<button onClick={increment} >+</button>
<button onClick={dincrement} >-</button>
<button onClick={reset}>reset</button>
</div>

)


}

export default Example3;


相关内容

  • 没有找到相关文章

最新更新