【问题标题】:Errors in parsing a JSON input in React在 React 中解析 JSON 输入时出错
【发布时间】:2018-07-18 09:22:24
【问题描述】:

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

这是它得到的数据:

{"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 未定义

在控制台中:

开发服务器已断开连接。必要时刷新页面。

我也试过这个:

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

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

那么我错过了什么?

【问题讨论】:

  • 我的猜测是,在您的第二个 .then(response 中,response 是未定义的,因为这就是 console.log() “返回”的内容。

标签: javascript reactjs axios


【解决方案1】:

TypeError: this.state.data.Value 未定义

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

检查这个sn-p:

let data = [];

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

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

您将 data 的初始值定义为一个数组,并且您正在从 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});

【讨论】:

  • isLoading 应该以true 开头,而不仅仅是因为this.setState() 是异步的。
  • @ChrisG 很好,谢谢,将在答案中添加:)
  • 感谢您的回答!问题已解决!但是1-为什么我需要返回响应?! 2-我在这个应用程序的控制台中仍然有错误“服务器已断开连接”,它可能来自这个代码吗?
  • @Ehsan 1- 因为您在 2nd .then 中执行 setState,所以如果您不从 1st 返回,则在 2nd 中将不可用另一个选项是在 1st .then 中执行 setState。 2-不确定那个错误,你能分享完整的错误信息吗?
猜你喜欢
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多