如何在这样的功能组件中使用LocalStorage
我知道如何在类组件中执行此操作,但是在这种情况下可以解决此问题吗?
错误:TypeError:存储库不是函数
<script>
//Require at least One Checkbox in each Step
$(document).ready(function OneBox() {
//Step-3
$("#step-3").on("change", "input", function(e) {
var status3 = ($("#step-3").find("input:checked").length == 0) ? "disabled" : "";
$("#step-3").find('button').prop('disabled', status3);
});
//Step-4
$("#step-4").on("change", "input", function(e) {
var status4 = ($("#step-4").find("input:checked").length == 0) ? "disabled" : "";
$("#step-4").find('button').prop('disabled', status4);
});
//Step-5
$("#step-5").on("change", "input", function(e) {
var status5 = ($("#step-5").find("input:checked").length == 0) ? "disabled" : "";
$("#step-5").find('button').prop('disabled', status5);
});
});
// End Require
</script>
答案 0 :(得分:0)
在您的first useEffect
中,repositories
是您的状态,即一个数组。不是功能。
此外,在您的second useEffect
中,您需要更正钩子中访问prevState的方式。
修复第一次使用效果
export default function Main() {
const [newRepo, setNewRepo] = useState('');
const [repositories, setRepositories] = useState([]);
const [clearInput] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
const localRepoItems = localStorage.getItem('repositories');
if (localRepoItems) {
setRepositories(JSON.parse(localRepoItems));
}
}, []); // do not give the dependency as repositories as it will go to infinite loop
});
要获取挂钩中的先前状态,可以编写一些自定义挂钩: 赞!
export const usePrevious = value => {
const ref = React.useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
组件中的用法:
const prevRepositories = usePrevious(repositories);
useEffect(() => {
if (prevRepositories.length !== repositories.length) {
localStorage.setItem('repositories', JSON.stringify(repositories));
}
}, [repositories]);