javascript - 在 React 中解析 JSON 输入时出错

标签 javascript reactjs axios

我正在编写一个 React 应用程序,它从 API 获取 JSON 数据并显示其中的一些内容。

这是它获取的数据:

{"id":6,"name":"5 Storey I=0.7","Value":1344981250,"NSt":5,"jRatio":"[0.2,0.4,0.4]","jEDR":"[0.02,0.1,0.5,1]"}

这是应用程序:

class App extends React.Component{
    constructor(props){
        super(props);
        this.state={
            data: [],
            isLoading: false,
            error: null,
        };
    }
    componentDidMount(){
        this.setState({isLoading: true});
        axios.get(API)
            .then(response => console.log(response.data.Value))
            .then(response => this.setState({data: response.data, isLoading: false}))
            .catch(response => this.setState({error: response.error, isLoading: false}));
    }
    render(){
        return (
            <div>
            <p>{this.state.error}</p>
            <p>{this.state.isLoading ? 'Loading...':'Loaded'}</p>
            <ul>{this.state.data.Value.toString()}</ul>
            </div>
        )
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

我在控制台中得到值“1344981250”,但页面抛出此错误:

TypeError: this.state.data.Value is undefined

在控制台中:

The development server has disconnected. Refresh the page if necessary.

我也尝试过这个:

this.state.data.map(obj => <li key={obj.toString()}>{obj.toString()}</li>)

这次没有出现任何错误,页面上没有显示任何内容。 (这个适用于对象数组,但当它只是一个对象时什么也不显示)

那么我错过了什么?

最佳答案

TypeError: this.state.data.Value is undefined

因为 data 是一个数组,[].Value(任何键)将是未定义的。

检查此片段:

let data = [];

console.log('data.Value = ', data.Value);

// this will throw error:
console.log('data.value.toString', data.Value.toString())


您将数据的初始值定义为数组,并且您正在从 api 调用获取该对象。解决方案是将初始值定义为:

data: {}

在render方法中,这样写:

<ul>{(this.state.data.Value || '').toString()}</ul>

您需要返回来自.then的响应:

axios.get(API)
  .then(response => {console.log(response.data.Value); return response;}   //<=== here
  .then(response => this.setState({data: response.data, isLoading: false}))
  .catch(response => this.setState({error: response.error, isLoading: false}))

编辑:

componentDidMount会在初始渲染后被调用,因此最好定义 isLoading: true 的初始值,之后您可以删除它:

this.setState({isLoading: true});

关于javascript - 在 React 中解析 JSON 输入时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51398247/

相关文章:

javascript - 延迟 javascript 执行直到 DOM 更改完成

javascript - 有条件地使第二次 axios 调用基于第一个发生

android - 在 native react 中调用本地主机 API(android 设备 : connected through local)

node.js - 代理在 create-react-app 和 axios 中不起作用

javascript - jQuery Datatables 按钮显示为链接..而不是按钮

javascript - 如何为 Windows Phone 创建 .XAP 扩展文件

javascript - 如何匹配包含javascript中动态组件的字符串

reactjs - 如何将 Fabric.js 与 React 结合使用?

javascript - 收到错误请求的资源上不存在 'Access-Control-Allow-Origin' header

css - 如何在带有反应的样式化组件中使用网格模板区域?