为了账号安全,请及时绑定邮箱和手机立即绑定

路由后保留数组状态挂钩

路由后保留数组状态挂钩

肥皂起泡泡 2023-03-03 15:52:16
我试图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 /valuesconst Continue = () =>{    history.push("/values");    history.go(0);}// Check if the item exist in the array after routing the pagefunction checkArray(val) {    return calculator.section.some(item => item === val);}建兴兴业 <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路由到另一个页面后如何保留钩子?现在它正在重置(我已经调试了计算器值来检查)。
查看完整描述

1 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

对于您的用例,我将创建一个新挂钩,该挂钩在挂载时从 localStorage 读取并将更改持久保存到 localStorage。

useHooks 的useLocalStorage钩子非常适合这里


查看完整回答
反对 回复 2023-03-03
  • 1 回答
  • 0 关注
  • 61 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信