首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在状态更改后,未重新呈现的响应组件

在状态更改后,未重新呈现的响应组件
EN

Stack Overflow用户
提问于 2022-09-13 21:35:28
回答 2查看 57关注 0票数 1

page状态更改时,它呈现错误,我单击类别链接,它检查链接是否存在于类别中,然后应该将page状态设置为category,同样,如果单击食谱链接,则应该将page状态设置为recipe

isRecipeisCategory的值是正确的,但只有在刷新页面后才能正确设置page状态。

它应该观察页面状态,如果变化了,它应该重新呈现组件。

如果页面状态发生变化,如何重新呈现组件?

代码语言:javascript
运行
复制
const categories = [
 {name: 'first', slug: 'first'}, 
 {name: 'second', slug: 'second'},
]

const recipes = [
 {name: 'firstRecipe', slug: 'firstRecipe'},
 {name: 'secondRecipe', slug: 'secondRecipe'},
]

const Categories = ({ categories, recipe, recipes }) => {
  const router = useRouter()
  const { slug } = router.query

  const isRecipe = !!recipes.find(recipe => recipe.slug === slug)
  const isCategory = !!categories.find(cat => cat.slug === slug)

  const [page, setPage] = useState('')

  useEffect(() => {
    !!isCategory && setPage('category')
    !!isRecipe && setPage('recipe')
    }, [page])
  
  return (
    <>
      <a href="/first"> category </a>
      <a href="/firstRecipe"> recipe </a>
      {page === 'category' && <Category /> }
      {page === 'recipe' && <Recipes /> }
    </>
  )
}

export default Categories
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-13 21:47:23

useEffect钩子的依赖关系实际上是isRecipeisCategory,所以效果应该依赖于[isRecipe, isCategory],而不是[page]

另外,由于帮助程序(isCategoryisRecipe)是从slug派生的,因此可以将它们移到钩子中,然后只需要[slug]来设置适当的挂钩依赖项。

注意:setPage不需要给钩子依赖列表,因为它是保证稳定的反应-省略它是安全的。

理想情况下,完全可以通过这样的简单计算来避免状态:

代码语言:javascript
运行
复制
page = null

if (isRecipe) {
  page = <Recipe />
} else if (isCategory) {
  page = <Category/>
}

...

<>
  ...
  {page}
<\>

实际上有三种可能的情况:菜谱页、类别页和其他与前两种不匹配的情况,通过呈现null,很可能会产生上面代码所预期的结果。

有较少的状态,钩子和突变,导致较少的移动部分,因此很可能更少的错误。

票数 1
EN

Stack Overflow用户

发布于 2022-09-13 21:43:39

尝试这样做,并添加到依赖项中:

代码语言:javascript
运行
复制
const categories = [
 {name: 'first', slug: 'first'}, 
 {name: 'second', slug: 'second'},
]

const recipes = [
 {name: 'firstRecipe', slug: 'firstRecipe'},
 {name: 'secondRecipe', slug: 'secondRecipe'},
]

const Categories = ({ categories, recipe, recipes }) => {
  const router = useRouter()
  const { slug } = router.query

  const isRecipe = !!recipes.find(recipe => recipe.slug === slug)
  const isCategory = !!categories.find(cat => cat.slug === slug)

  const [page, setPage] = useState('')

  useEffect(() => {
    !!isCategory && setPage('category')
    !!isRecipe && setPage('recipe')
    }, [page, isRecipe, isCategory  ])
  
  return (
    <>
      <a href="/first"> category </a>
      <a href="/firstRecipe"> recipe </a>
      {page === 'category' && <Category /> }
      {page === 'recipe' && <Recipes /> }
    </>
  )
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73709389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档