在React中使用Axios

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
//FormData和Payload是瀏覽器傳輸數(shù)據(jù)給接口的其中兩種格式,這兩種方式瀏覽器是通過Content-Type來進(jìn)行區(qū)分的,如果是application/x-www-form-urlencoded,則為formdata方式,如果是application/json方式,則為payload方式。需要轉(zhuǎn)換成formdata方式,則要下載qs進(jìn)行轉(zhuǎn)換
  import qs from 'qs'
   axios.post('/user-server/login/userLogin',qs.stringify({
        userName:me.refs.name.value,
        password:me.refs.password.value
    })).then(res => {
        console.log(res);
    })

代碼是用的backbone和zepto,主要是content-type,還需要使用JSON對象進(jìn)行轉(zhuǎn)化一下。

class FetchDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }
  componentDidMount() {
    axios.get(`http://www.reddit.com/r/${this.props.subreddit}.json`)
      .then(res => {
        const posts = res.data.data.children.map(obj => obj.data);
        this.setState({ posts });
      });
  }
  render() {
    return (
      <div>
        <h1>{`/r/${this.props.subreddit}`}</h1>
        <ul>
          {this.state.posts.map(post =>
            <li key={post.id}>{post.title}</li>
          )}
        </ul>
      </div>
    );
  }
}
ReactDOM.render(
    <FetchDemo subreddit="reactjs"/>,
  document.getElementById('root')
);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容