将axios(JSON)响应存储在数组中

时间:2019-08-14 19:16:56

标签: reactjs

我有一个数组,另一个文件正在使用该数组来映射内容。我最初将值硬编码到此数组中,但现在我想将axios get调用集成到以检索数据,然后将响应中的信息存储到数组中。我可以使用正确的数据成功获取JSON响应,但是我一直坚持将JSON响应数据添加到数组中。任何帮助将不胜感激

let theArray = [
{
id: '',
name: '',
},]

useEffect(() => {
        axios
            .get(`/api/data`)
            .then(res => {
                //? need to store res.data.id to theArray.id, and res.data.name to theArray.name
            })
    }, [])

4 个答案:

答案 0 :(得分:2)

您可以简单地将响应推送到数组,但是必须从一个空数组开始,否则,您硬编码的第一个元素将没有任何数据。

let theArray = []

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

答案 1 :(得分:1)

这是另一种解决方案,我认为@Sylens解决方案是一个很好的解决方案,这只是根据需要构造代码的问题

let theArray = []

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

答案 2 :(得分:0)

如果仅修改第一个元素:

let theArray = [{ id: '',  name: '',},]

useEffect(() => {
        axios
            .get(`/api/data`)
            .then(res => {
                theArray[0].id = res.data.id
                theArray[0].name = res.data.name
            })
    }, [])

答案 3 :(得分:0)

如果您的数据为json格式,则应等待信息被解析,如下所示:

let theArray = [
    {
        id: '',
        name: '',
    },
];

useEffect(() => {
    axios
        .get(`/api/data`)
        .then(res => res.json())
        .then((result) => {
            theArray[0].id = result.id;
            theArray[0].name = result.name;
        })
}, []);

编辑:如果要添加新数据,只需将其推入数组

theArray.push({
    id: result.id,
    name: result.name,
})