reactjs - 添加设置状态更改会导致 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
}
解决方案
解决此问题的一种方法是对过滤后的帖子使用另一种状态。并保留原始帖子以备将来使用:
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])
推荐阅读
- twilio - twilio 没有收到来自网站的消息
- visual-studio-code - Visual Studio代码集成终端无响应
- oracle - 更好的是在 for 循环中多次删除
- java - 如何在android webview中保存上次访问的url?
- aws-fargate - 如何将 Fargate 与 Media convert 连接起来?
- python - 如何比较python3中的两个csv文件?
- bash - 为什么此 YAD 列表代码无法正常工作?
- unix - Vim:在普通模式下切换键盘布局
- angular - Spring Gateway 如何路由深度 SPA 链接
- asp.net-core - 将 blazor 组件添加到现有 Asp.net 核心项目的问题