Javascript React-如何应用钩子值的本地存储
我将该包用于我的项目的个人目的,问题是在刷新页面时无法保存值,我尝试使用本地存储,但无法保存 正如您所理解的,我需要使用本地存储来保存值,此外,我将在codesandbox上留下一个指向我的值的链接 SideBarBlurChange.jsxJavascript React-如何应用钩子值的本地存储,javascript,reactjs,redux,react-hooks,local-storage,Javascript,Reactjs,Redux,React Hooks,Local Storage,我将该包用于我的项目的个人目的,问题是在刷新页面时无法保存值,我尝试使用本地存储,但无法保存 正如您所理解的,我需要使用本地存储来保存值,此外,我将在codesandbox上留下一个指向我的值的链接 SideBarBlurChange.jsx import React, {useEffect, useState} from "react"; import {getTrackBackground, Range} from "react-range"; co
import React, {useEffect, useState} from "react";
import {getTrackBackground, Range} from "react-range";
const STEP = 0.1;
const MIN = 0;
const MAX = 100;
export default function SideBarBlurChange(props) {
const [values, SetValues] = useState([20])
const SaveChanges = () => {
alert(values)
}
return (
<>
<div
style={{
display: "flex",
justifyContent: "center",
flexWrap: "wrap",
}}
>
<Range
values={values}
step={STEP}
min={MIN}
max={MAX}
onChange={(values) => SetValues(values)}
renderTrack={({ props, children }) => (
<div
onMouseDown={props.onMouseDown}
onTouchStart={props.onTouchStart}
style={{
...props.style,
height: "36px",
display: "flex",
width: "100%"
}}
>
<div
ref={props.ref}
style={{
height: "5px",
width: "100%",
borderRadius: "4px",
background: getTrackBackground({
values: values,
colors: ["#548BF4", "#ccc"],
min: MIN,
max: MAX
}),
alignSelf: "center"
}}
>
{children}
</div>
</div>
)}
renderThumb={({ props, isDragged }) => (
<div
{...props}
style={{
...props.style,
height: "42px",
width: "42px",
borderRadius: "4px",
backgroundColor: "#FFF",
display: "flex",
justifyContent: "center",
alignItems: "center",
boxShadow: "0px 2px 6px #AAA"
}}
>
<div
style={{
height: "16px",
width: "5px",
backgroundColor: isDragged ? "#548BF4" : "#CCC"
}}
/>
</div>
)}
/>
<output style={{ marginTop: "30px" }} id="output">
{values[0].toFixed(1)}
</output>
<button onClick={() => SaveChanges()}>Save</button>
</div>
</>
);
}
import React,{useffect,useState}来自“React”;
从“react Range”导入{getTrackBackground,Range};
常数步长=0.1;
常数MIN=0;
常数MAX=100;
导出默认功能更改(道具){
const[values,SetValues]=useState([20])
const SaveChanges=()=>{
警报(值)
}
返回(
设置值(值)}
renderTrack={({props,children})=>(
{儿童}
)}
renderThumb={({props,isDraged})=>(
)}
/>
{values[0].toFixed(1)}
SaveChanges()}>Save
);
}
我认为您的主要问题是localStorage除了字符串之外不存储任何内容。您将需要parseInt,然后检查以确保localStorage不为null。你能试试这个,看看是否有效吗
const ls = parseInt(window.localStorage.getItem('values'));
const [values, SetValues] = useState(ls ? [ls] : [20]);
const SaveChanges = () => {
alert(values);
localStorage.setItem('values', values);
}