我设法从服务器(mssql模块)中检索JSON数据,但是当我尝试发出Axios请求时,无法获取数据以将其呈现为App组件。
这是来自localhost:// 5000(服务器端)的原始JSON数据。 我必须将// //放在下面,因为它在问题中无法正确显示。
//{"recordsets":[[{"NAME":"TOM"},{"NAME":"RUBY"},{"NAME":"JANE"},
//{"NAME":"ALI"},
//{"NAME":"CELINE"},{"NAME":"JACK"},
//{"NAME":"KANE"},{"NAME":"BANE"},
//{"NAME":"DANNY"},{"NAME":"ROCK"}]],"recordset":[{"NAME":"TOM"},
//{"NAME":"RUBY"},{"NAME":"JANE"},
//{"NAME":"ALI"},{"NAME":"CELINE"},
//{"NAME":"JACK"},{"NAME":"KANE"},
//{"NAME":"BANE"},{"NAME":"DANNY"},
//{"NAME":"ROCK"}],"output":{},"rowsAffected":[10]}
//Here's the Result component code
import React from "react";
import PropTypes from "prop-types";
class Result extends React.Component {
render() {
const { name, isLoading } = this.props;
const details = (
<div>
<h4>{name}</h4>
</div>
);
const loadingMessage = <span>Loading...</span>;
return (
<div>
{isLoading ? loadingMessage : details}
</div>
);
}
}
Result.propTypes = {
name: PropTypes.string,
isLoading: PropTypes.bool
};
export default Result;
//App component code
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import './App.css';
import Result from './component/Result';
import API from './routes/api/api'
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
name: null
};
}
render() {
const { isLoading, name } = this.state;
return (
<div className="welcome">
<h1>Welcome to the new RFQ System - BETA version 0.0.0</h1>
<Result isLoading={isLoading} name={name} />
</div>
);
}
async componentDidMount() {
try {
let userData = await API.get('/', {
params: {
recordsets: 10, //number of results
inc: 'NAME'
}
});
// Parse the results for ease of use.
userData = userData.data.recordsets[0][0];
//Update state with new data and re-render our component.
const name = userData.name;
this.setState({
...this.state, ...{
isLoading: false,
name
}
});
}
catch (e) {
console.log(`? Axios request failed: ${e}`);
}
};
}
export default App;
ReactDOM.render(<App />, document.getElementById('root'));
我只会在页面上显示“正在加载...”,而不是实际结果。
现在,我只想先显示数据,然后再将其放入数组以呈现列表。
答案 0 :(得分:0)
我尝试使用axios运行相同的代码,它成功运行。下面是我尝试过的:
async componentDidMount() {
try {
let userData = await axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => res.data);
userData = userData[0];
//Update state with new data and re-render our component.
const name = userData.name;
this.setState({
...this.state,
...{
isLoading: false,
name
}
});
} catch (e) { }
}
我想您的API退货有问题。