React和React-native踩坑记

react坑:

1、fetch请求cookie跨域问题
使用creat-react-app时,其中的react-script已经默默帮你做了很多事,都帮你配置好了:

React, JSX, ES6, and Flow syntax support.
Language extras beyond ES6 like the object spread operator.
Import CSS and image files directly from JavaScript.
Autoprefixed CSS, so you don’t need -webkit or other prefixes.
A build script to bundle JS, CSS, and images for production, with sourcemaps.
A dev server that lints for common errors.

所以你发现你找不到webpack相关的配置文件。那么遇见跨域问题,例如cookie跨域时需要配置代理该怎么办呢?
解决方法:
首先,配置代理。去package.json里添加一个proxy部分,如下:

clipboard.png

  "proxy": {
    "/*": {  //星号代所有,也可以是 /xxx/* 或 /xxx/xxx/*
      "target": "http://10.0.209.147", //你获取数据的服务器地址
      "ws": true, 
      "secure": true,
      "changeOrigin": true,
      "withCredentials": true, //跨域请求设置为true
    }
  }

接下来,在fetch方法中添加跨域请求凭证credentials: 'include'

例如下面的登录例子:

const url= "/xxxx/xxxxx/xxxx"; 
//请求地址,因为配置了代理,所以最开始处省略了主地址,直接以斜杠开始

let formData = new FormData();
formData.append('name', 'admin'); //参数,用户名
formData.append('password', '123456'); //参数,密码
fetch(url, {
    method: 'post', //post方法
    body: formData, //传参
    credentials: 'include',  //此处最为重要,请求代理凭证
}).then(function (res) {
    return res.json();
}).then(function (json) {
    alert('cookie内容:'); //此处可以尝试alert一下cookie里所有的内容
    alert(json); //后台返回的数据
});

2、react中creat-react-app的项目,完成后打包页面访问空白
npm run build 之后会自动生成一个build文件夹,打开其中的index.html发现页面空白且报错提示文件没找到。放到服务器上仍然是空白的无法访问。
原来是因为路径问题,简单配置一下即可。上文提到过react-script已经帮我们做好了很多事,方便在此,麻烦也在此。这个问题仍需更改其中的配置文件:

路径:my-app\node_modules\react-scripts\config

修改path.js文件,红框部分是修改后的结果,如下图:

clipboard.png

然后再重新npm run build 即可

react-native坑:

1、react-native中的警告:

Warning: Can only update a mounted or mounting component. This usually means you called setState,replaceState, or forceUpdate on an unmounted component. This is a no-op.
Please check the code for the xxx component.

可能对一个没有装载的组件执行了setState()操作,在React的官网里有一个解决方案,isMounted
这种情况大多出现在callback中,异步请求返回数据之前,组件可能就已经被卸载了,等数据回来再使用setState就会警告,所以应该手动在componentWillUnmount里去取消callback

解决办法:

componentWillUnmount() {
    this.setState = (state, callback) => {
        return;
    };
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值