我尝试在路由到另一个页面后保持/保留反应useState
钩子,现在假设我有一个名为sections
的数组保存在useState
钩子中,位于数组我内部有3个物品
广告, 促进, 建立
当我路由到另一个渲染时,useState
挂钩的值正在重置,其中包括数组。
相关功能
const [calculator, setCalculator] = useState({section: [], graphic: false}); //Sections array inside
// Responsible to add item to the array, also promote and ads, just short version so you can understand
function addPath(section){
if(section === "build"){
if(calculator.section.some(val => val === "build")){
let filteredArray = calculator.section.filter(item => item !== 'build')
setCalculator({section: filteredArray});
$('.build').removeClass('active');
}
else{
var joined = calculator.section.concat('build');
setCalculator({ section: joined })
$('.build').addClass('active');
}
}
}
//Route from /start to /values
const Continue = () =>{
history.push("/values");
history.go(0);
}
// Check if the item exist in the array after routing the page
function checkArray(val) {
return calculator.section.some(item => item === val);
}
JSX
<Route path="/start">
<p className="secondary">
בחר מסלול רלוונטי (ניתן לבחור יותר מאחד)
</p>
<Row className="margTop">
<Col lg="4"><img id="firstSelectors" className="build" onClick={() => addPath('build')} src={Code} alt="בניית אתרים" /></Col>
<Col lg="4"><img id="firstSelectors" className="promote" onClick={() => addPath('promote')} src={Promotion} alt="קידום אתרים" /></Col>
<Col lg="4"><img id="firstSelectors" className="ad" onClick={() => addPath('ad')} src={Advertise} alt="שיווק דיגטלי" /></Col>
</Row>
<button onClick={Continue}>המשך</button>
</Route>
<Route path="/values">
{checkArray('ad') ? 'yes' : 'no'}
</Route>
在路由到另一页后如何保留useState
钩子?现在它正在重置(我已经调试了计算器的值来进行检查)。
答案 0 :(得分:0)
对于您的用例,我将创建一个新的钩子,该钩子从安装时的localStorage读取并保留对localStorage的更改。
useHooks中的useLocalStorage钩子非常适合