首页 > 解决方案 > 如何使用 React 在渲染中访问数组?

问题描述

我对 React 很陌生,在尝试解决编码问题时,我在另一个问题上看到了这段代码(我尝试询问那些回答了这个问题但没有收到回复的人,因为它在不久前得到了回答):

let theArray = []

functionName(() => {
        axios
            .get(`/api/data`)
            .then(res => {
                const newItem = {
                  id: res.data.id,
                  name: res.data.name,
                };
                theArray.push(newItem);
             })
    }, [])

有人知道如何在 render() 中访问 theArray 吗?我尝试做 theArray[0].id,但出现错误。我也试过this.state.theArray[0].id,但也出错(数组有4个元素,每个元素都有自己的id和名称)

提前感谢您的帮助!

标签: javascriptnode.jsreactjsaxios

解决方案


你可以写这样的东西。

  const [theState, setState] = useState([])

   functionName(() => {
        axios
            .get(`/api/data`)
            .then(res => {
                const newItem = {
                  id: res.data.id,
                  name: res.data.name,
                };
                setState([...theState, newItem])
             })
    }, [])

推荐阅读