react学习笔记 - 小案例

UI框架用的ant design

npm i antd -S
全部引入文件很大,建议按需引入

1. antd的样式文件引入失效

webpack.config.js中针对antd重新配置样式文件。

      // 针对antd样式专用配置文件
      { test: /\.css$/, use: ['style-loader', 'css-loader'], exclude: /src/  },

上面针对src中的文件配置样式模块化,下面针对antd重新配置样式文件。

2.按需加载

使用[babel-plugin-import]

3. fetch

fetch的MDN
get请求

    fetch('http://example.com/movies.json')
    .then(res => {
        return res.json()
      }
    )
    .then(data => {
      console.log(data)
    })

post请求

  sendMsg() {
    var sendData = new URLSearchParams()
    sendData.append('name', 'zs')
    fetch('http://39.106.32.91:3000/api/post',{
      method: 'POST',
      body: sendData
    })
    .then(res => res.json())
    .then(data => console.log(data))
  }

fetch jsonp解决跨域问题,适用于服务端没有cors的情况
npm i fetch-jsonp -S
直接使用

  import fetchJSONP from 'fetch-jsonp'
  sendMsg() {
    fetchJSONP('https://api.apiopen.top/getSongPoetry?page=1&count=20')
    .then(res => {
        return res.json()
      }
    )
    .then(data => {
      console.log(data)
    })
  }

报错,待解决

结合asyncawait一起使用

index.js

import fetchJSONP from 'fetch-jsonp'
React.Component.prototype.$http = fetchJSONP

App.jsx

  sendMsg = async () => {
    const res = await this.$http('https://api.apiopen.top/getSongPoetry?page=1&count=20')
    const data = await res.json()
    console.log(data)
  }

同上报错,待解决

4.快速搭建项目

create-react-app
其他配置,如按需加载等,参考这里

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。