如何在功能组件React中使用本地存储

时间:2020-04-15 18:45:34

标签: javascript reactjs local-storage react-hooks

如何在这样的功能组件中使用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>

1 个答案:

答案 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]);