亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法在反應 js 中顯示從 rest API 獲取的數據

無法在反應 js 中顯示從 rest API 獲取的數據

月關寶盒 2022-06-15 17:04:33
我有通過 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>    )  }}
查看完整描述

3 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

您并沒有真正設置狀態,或者我還沒有看到那種語法。


通常,我會做類似...


this.setState({ stateProp: valueToAssign });

所以,在你的情況下......


this.setState({ d: res.data });

我認為您缺少帶類的構造函數。例如來自反應站點。


constructor(props) {

    super(props);

    // Don't call this.setState() here!

    this.state = { counter: 0 };

    this.handleClick = this.handleClick.bind(this);

}

所以在你的情況下......


constructor(props) {

    super(props);


    this.state = { d: [] };


}

為了確保我分配了正確的值,我會做一個“console.log(res.data)”來檢查。


查看完整回答
反對 回復 2022-06-15
?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

它確實取決于 API 響應的格式。您不能像這樣渲染對象或數組:


render() {

  const object = {foo: 'bar'};

  return (

    <div>

      {object}

    </div>

}

但是你可以像這樣渲染它:


render() {

  const object = {foo: 'bar'};

  return (

    <div>

      {object.foo}

    </div>

}


查看完整回答
反對 回復 2022-06-15
?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

import axios from 'axios';


export default class PersonList extends React.Component {

  constructor(props) {

super(props);


this.state = { key: []};

}


  componentDidMount() {

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

    .then(res => {

      this.setState(key: res.data);

    })

}


  render() {

    return (

      <ul>

      { this.state.key}

      </ul>

    )

  }

}


查看完整回答
反對 回復 2022-06-15
  • 3 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號