Reactjs 如何在react js中从json数组获取数据

Reactjs 如何在react js中从json数组获取数据,reactjs,Reactjs,我从api中获取json,但它没有转换为数组。以前我获取了值,但从这段代码中我没有获取值 这是我的代码: componentWillMount() { let initialFilename; fetch('http://localhost/Generator/FetchfileDetails.php') .then(response=>{ return response.json(); }).then(data=&g

我从api中获取json,但它没有转换为数组。以前我获取了值,但从这段代码中我没有获取值

这是我的代码:

componentWillMount() {
    let initialFilename;
    fetch('http://localhost/Generator/FetchfileDetails.php')
        .then(response=>{
            return response.json();
        }).then(data=>{
            alert(data.filename);
        });
}

my json中的键值是filename是如何存储在数组中的???

您可以尝试而不是响应。json()您可以执行以下操作:

fetch("http://localhost/Generator/FetchfileDetails.php") .then(response=>{ return JSON.parse(response) }).then(data=>{ alert(data);})


另外,如果您说响应应该是一个数组,那么您不能使用data.filename,您必须使用data['filename',data.filename用于对象响应

您可以尝试代替response.json(),您可以执行以下操作:

fetch("http://localhost/Generator/FetchfileDetails.php") .then(response=>{ return JSON.parse(response) }).then(data=>{ alert(data);})


另外,如果您说响应应该是一个数组,则不能使用data.filename,必须使用data['filename',data.filename用于对象响应

首先要记住不要使用componentWillMount()方法获取数据

参考:

使用以下命令:

componentDidMount(){  
     fetch("http://localhost/Generator/FetchfileDetails.php") 
        .then(res=> res.json())
        .then(data=>{ //here you can set data to state })
}

首先要记住,不要使用componentWillMount()方法获取数据

参考:

使用以下命令:

componentDidMount(){  
     fetch("http://localhost/Generator/FetchfileDetails.php") 
        .then(res=> res.json())
        .then(data=>{ //here you can set data to state })
}

我推荐你使用axios软件包来获取数据,它非常容易使用

axios.get('API').then(response=>{console.log(response)})
您可以在componentDidMount函数中插入此代码


如果您想查看完整的axios文档,

我建议您使用axios软件包获取数据,它非常容易使用

axios.get('API').then(response=>{console.log(response)})
您可以在componentDidMount函数中插入此代码

如果你想看完整的axios文档,

[{slno:“2”,“filename:“newfile1text”,“filepath:“Uploads\/TextFiles\/newfile1text”},{slno:“4”,“filename:“newfile2text”,“filepath:“Uploads\/TextFiles\/newfile2text”}]我的json是这样的,我没有得到不精确的文件名。[{“slno:“2”,“filename:“newfile1text”,“filepath”:“Uploads\/TextFiles\/newfile1text”},{“slno”:“4”,“filename”:“newfile2text”,“filepath”:“Uploads\/TextFiles\/newfile2text”}]我的json是这样的,我没有得到文件名,我得到的是未定义的。。