无法在反应 js 中显示从 rest API 获取的数据

我有通过 rest api 获取数据的反应代码,但我无法显示 JSon 数据。请找到下面的代码


从“反应”导入反应;


import axios from 'axios';


export default class PersonList extends React.Component {

  state = {

    d: []

  }


  componentDidMount() {

    axios.get(`http://localhost:8080/login/?username=abc&password=welcome1`)

    .then(res => {

      const d = res.data;

      this.setState({ d });

    })

  }


  render() {

    return (

      <ul>

      { this.state.d}

      </ul>

    )

  }

}


月关宝盒
浏览 84回答 3
3回答

炎炎设计

您并没有真正设置状态,或者我还没有看到那种语法。通常,我会做类似...this.setState({ stateProp: valueToAssign });所以,在你的情况下......this.setState({ d: res.data });我认为您缺少带类的构造函数。例如来自反应站点。constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; // Don't call this.setState() here!&nbsp; &nbsp; this.state = { counter: 0 };&nbsp; &nbsp; this.handleClick = this.handleClick.bind(this);}所以在你的情况下......constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = { d: [] };}为了确保我分配了正确的值,我会做一个“console.log(res.data)”来检查。

慕田峪4524236

它确实取决于 API 响应的格式。您不能像这样渲染对象或数组:render() {&nbsp; const object = {foo: 'bar'};&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {object}&nbsp; &nbsp; </div>}但是你可以像这样渲染它:render() {&nbsp; const object = {foo: 'bar'};&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; {object.foo}&nbsp; &nbsp; </div>}

富国沪深

import axios from 'axios';export default class PersonList extends React.Component {&nbsp; constructor(props) {super(props);this.state = { key: []};}&nbsp; componentDidMount() {&nbsp; &nbsp; axios.get(`http://localhost:8080/login/?username=abc&password=welcome1`)&nbsp; &nbsp; .then(res => {&nbsp; &nbsp; &nbsp; this.setState(key: res.data);&nbsp; &nbsp; })}&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; { this.state.key}&nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; )&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java