【问题标题】:How do I store and update an array using hooks immediately after the component is loaded?如何在组件加载后立即使用钩子存储和更新数组?
【发布时间】:2020-01-13 14:23:14
【问题描述】:

我正在使用功能组件和钩子。第一次渲染组件后,在 useEffect 函数中,我有一个循环来从产品列表中获取唯一类别。

一旦这些类别被提取出来,我将它们存储在一个数组中,以组件状态为setCategoriesState。但是,就目前而言,除非重新渲染组件,否则状态不会反映更新的类别列表。有没有更好的方法来做到这一点?

const [categoriesState, setCategoriesState] = useState([])
var categories = []

useEffect(() => {
  for (let i = 0; i < props.products.items.length; i++) {
    if (categories.indexOf(props.products.items[i].category) === -1) {
      categories = [...categories, props.products.items[i].category]
    }
  }

  setCategoriesState(categories)

}, [])

这就是我使用 categoriesState 的方式

{categoriesState.map((cat) => <Text >{cat}</Text>)}

【问题讨论】:

  • 您在react-nativereactjs 中使用它,因为您将两者都添加为标签。
  • 我正在使用 React Native
  • 但是您正在使用setCategoriesState 更新您的状态,这意味着您的组件将重新渲染!!
  • 你是如何使用categoriesState的?
  • @WillJenkins {categoriesState.map((cat) =&gt; &lt;Text &gt;{cat}&lt;/Text&gt;)}

标签: javascript react-native react-hooks


【解决方案1】:

您应该在useEffect 中包含您的categories 声明,并传播您的categoriesState

const [categoriesState, setCategoriesState] = useState([])

useEffect(() => {
  let categories = [...categoriesState]

  for (let i = 0; i < props.products.items.length; i++) {
    if (categories.indexOf(props.products.items[i].category) === -1) {
      categories = [...categories, props.products.items[i].category]
    }
  }

  setCategoriesState(categories)

}, [])

【讨论】:

  • 这看起来是个好主意。 useEffect 上的文档中有一条注释可能有助于理解为什么您的类别状态不更新:reactjs.org/docs/…
  • 正在调查。
猜你喜欢
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 2021-03-24
  • 2019-02-26
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 2020-06-01
相关资源
最近更新 更多