ReactJS - 使用 useState 数组推送方法

fjurr

这里的目的是拥有一组频道 ID,我可以在其中使用来自我的 Firebase 的信息填充他。

我有这样的组件:

export default function Component() {

const [channelsId, setChannelsId] = useState([])

// and I call this function passing my state
  useEffect(() => {
    getChannelsIds(someId, channelsId, setChannelsId)
  }, [])

功能:

export const getChannelsIds = (someId, channelsId, setChannelsId) => {
  try {
    firestore.collection("channels").where("someId", "==", someId).get().then(querySnapshot => {
      querySnapshot.forEach(doc => {
        setChannelsId([...channelsId, doc.data().id])
      })
    })
  } catch (err) {
    toast.error('Error while trying to get the channel.')
  }
}

它不起作用,因为我的 channelsId 状态被覆盖,我只有最后一个 channelId,console.log 屏幕截图

在此处输入图片说明

加布里埃尔·彼得里奥利

您应该使用功能更新

export const getChannelsIds = (someId, channelsId, setChannelsId) => {
  try {
    firestore.collection("channels").where("someId", "==", someId).get().then(querySnapshot => {
      querySnapshot.forEach(doc => {
        setChannelsId(ids => [...ids, doc.data().id]);
      })
    })
  } catch (err) {
    toast.error('Error while trying to get the channel.')
  }
}

或者更好的是,您可以首先使用新数据创建一个数组,并且只更新一次状态。

export const getChannelsIds = (someId, channelsId, setChannelsId) => {
    try {
      firestore.collection("channels").where("someId", "==", someId).get().then(querySnapshot => {
          const newChannelIds = querySnapshot.map(doc => doc.data().id);
          setChannelsId([...channelsId, ...newChannelIds);
          });
      }
      catch (err) {
        toast.error('Error while trying to get the channel.')
      }
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 Reactjs 中使用 UseState

Reactjs 使用 useState 导致 axios 请求循环

使用 reactjs useState 时出现错误

ReactJS - 使用 useState 钩子维护数值

使用 useState reactjs 更改日期

使用useState钩子未设置状态 ReactJS

使用ReactJS在数组中推送项目

React-如何使用useState在对象中推送数组

使用usestate数组时,将类型为checkbox的reactjs输入元素限制为2

如何使用useState更新数组?

使用 useState 更新数组对象

使用 ReactJS Hooks 通过 useState 增加价值

使用useState時ReactJS無限請求循環

Reactjs 如何使用 useEffect 来处理 useState 的许多变化

如何在reactjs中将usestate与对象一起使用?

无法在 reactjs 中使用 useState 设置状态数据

在 usestate hook 的帮助下使用 reactjs 获取 textarea 字符数

ReactJS:使用useState管理多个复选框输入

使用 useState 钩子单击按钮不会更新 reactjs 状态

使用 ReactJS 的 useState 钩子设置变量不起作用

(Reactjs) 使用 useEffect 和 useState 获取数据时的“延迟”

如何使用setState reactjs将对象推送到数组内?

reactjs 组件控制与 useState

如何使用 React 中的 useState 钩子将保存状态的对象推送到状态数组中?

使用挂钩(useState)从数组中删除对象

使用 React useState 更改对象数组

如何使用useState设置对象数组的状态?

使用数组作为反应钩子 useState

如何使用useState Reactjs来控制打开或关闭Modal Bootstrap?(不使用ReactBootstrap库)