首页 > 解决方案 > 添加设置状态更改会导致 React 中的无限循环

问题描述

我正在尝试使用 gatsby (react) 和 Fuse.js 创建离线模糊搜索,但我遇到了使用 setState 存储“搜索”字词的问题。

我收到以下错误:重新渲染太多。React 限制了渲染的数量以防止无限循环。

我不确定如何保存新状态(下面的代码)

 const [posts, setPosts] = useState(null)
    useEffect(() => {
        fetch("/index.json")
            .then(response => response.json())
            .then(function(data) {
                setPosts(data.data.allContentfulPost.edges)
            })
    }, [])

    if (posts) {
        var list = posts //returns 326 items
        var options = {
            shouldSort: true,
            threshold: 0.6,
            location: 0,
            distance: 100,
            maxPatternLength: 32,
            minMatchCharLength: 1,
            keys: ["node.title", "node.meta"],
        }
        var fuse = new Fuse(list, options)
        var results = fuse.search("marketing") //returns 11 items
        setPosts(results) //causes infinite loop
    }

标签: reactjsgatsby

解决方案


解决此问题的一种方法是对过滤后的帖子使用另一种状态。并保留原始帖子以备将来使用:

const [posts, setPosts] = useState([]);
const [filteredPosts, setFilteredPosts] = useState([]);

useEffect(() => {
    fetch("/index.json")
        .then(response => response.json())
        .then(function(data) {
            setPosts(data.data.allContentfulPost.edges)
        })
}, []);

useEffect(() => {
  var options = {
      shouldSort: true,
      threshold: 0.6,
      location: 0,
      distance: 100,
      maxPatternLength: 32,
      minMatchCharLength: 1,
      keys: ["node.title", "node.meta"],
  }
  var fuse = new Fuse(posts, options)
  var results = fuse.search("marketing") //returns 11 items
  setFilteredPosts(results) 
}, [posts])

推荐阅读