React native开发中遇到的坑

1.react-native-vector-icons集成,显示图片显示问题。

要使用字体库的字体,除了执行npm install react-native-vector-icons --save 之外,

1.npm install react-native-vector-icons --save
2.
react-native link react-native-vector-icons
// 或者
npm install -g rnpm
rnpm link react-native-vector-icons

还需要再Android与iOS工程里面进行相应的配置,Android的话需要在 android/app/build.gradle 中添加:apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
如果在android原生应用集成了react native形式,路径为"apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"",不然检测不到。资料
使用方法:

1.import Icon from "react-native-vector-icons/Ionicons"

image.png

Icon图标链接

2.import FontAwesome from "react-native-vector-icons/FontAwesome"

image.png

FontAwesome图标链接

 <Icon name="md-american-football" size={64}></Icon>
3.import EIcon from "react-native-elements/src/icons/Icon";

使用 react _native_elements的图标,使用type,来加载不同类型下的。
elements图标
eg:

 <EIcon
      reverse  //反转
      name='ac-unit'
      type='MaterialIcon'
      color='#517fa4'
      />
image.png
2.webstrom设置React native代码模板链接
3.循环遍历,提示Warning: Each child in an array or iterator should have a unique "key" prop. Check the render ...

解决方法:循环的时候加个key={i} 虽然并没啥用,但是必须加
image.png
4.react-native-scrollable-view详解是详解

在使用sctollable-view的过程中, renderTabBar={()=><DefaultTabBar />}默认的是一页分布排列,当数量过多,就显示不出来,换成 renderTabBar={()=><ScrollableTabBar />},能滚动。就能正常显示了。但是还一直说为啥没数据。坑了。

5.调试技巧参考资料 资料2

工具

6.解决 调试跨域的问题

下载google浏览器跨域插件链接。密码:fxtx
打开更多工具===扩展插件,脱动下载好的插件进行安装,
重新启动浏览器。就没有错误了。正常显示

image.png

7.Debug JS Remotely google浏览器提示 无法找到文件

重新安装了下浏览器,就可以了、

8.fetch 中的POST请求传递的请求参数没起作用。

后使用fromData()形式提交,不需要header,就能请求成功

        let formData = new FormData();
        formData.append('pid', this.state.pid);
        fetch(NET_URL, {
            method: 'POST',
            body: formData
        }).then((response)=>response.json())
            .then((responseData)=>{
                this.setState({
                    new_tabs:responseData.data
                })
            })
            .catch((error)=>{

        })

这样子就能正常显示了。

9.警告3:调试警告
image.png

看下报的警告就知道调试程序在这个窗口导致运行缓慢,所以建议你换一个单独新的窗口进行调试

10.Uncaught SyntaxError: Unexpected token
image.png

应该是用法的错误,我遇到过,最后是因为导入的路径的问题。一般是JS代码出错了,要么是样式或者布局不正确引起

11.
image.png

该问题是因为在return 中注释的问题链接

12.Warning: Failed child context type: Invalid child context virtualizedCell.cellKey of type number supplied to CellRenderer, expected string.

image.png

参考:资料
image.png
,就没有了。

13.unable to connect with remote debugger Timeout while connecting to remote debugger

image.png

,不管是真机还是模拟器都要在setting中设置自己的ip地址 eg:10.1.1.100:8081
10.1.1.100是你的ip地址,在cmd窗口 ipconfig 查看自己的ip地址
image.png

14.出现bundling failed: NotFoundError: Cannot find entry file index.android.js in any of the roots

For Android, go to your Module: app’s build.gradle and add the following above the line: apply from: “../../node_modules/react-native/react.gradle”
project.ext.react = [
entryFile: “index.js”
]
In MainApplication.java, you need to override another function in the anonymous ReactNativeHost class by adding this:
@Override
protected String getJSMainModuleName() {
return "index";
}

16. SyntaxError: Unexpected token < in JSON at position 0

使用fetch的get,返回的不是json字符串,导致

17.在react native界面点击物理返回键,把当前的Activity销毁了,React native中的js,没有返回。其实在集成的时候,RN都给我们做好了,只是乱改代码导致错误,还半天没解决到。

书读百遍,其义自见(xian)

感谢文章的小伙伴从Android到React Native开发(二、通信与模块实现)
DefaultHardwareBackBtnHandler
DefaultHardwareBackBtnHandler接口,通过它我们可以整体了解,React Native从android端,到JS端对back按键事件的处理。
首先Activity需要继承DefaultHardwareBackBtnHandler接口。DefaultHardwareBackBtnHandler只有一个invokeDefaultOnBackPressed方法。
ReactInstanceManager在onHostResume(Activity activity, DefaultHardwareBackBtnHandler defaultBackButtonImpl);中需要传入activity和handler接口。
ReactInstanceManager.onBackPressed()会通过DeviceEventManagerModule,向js端发送了"hardwareBackPress"消息。

[热点]React Native对于android back按键,是在onBackPressed中,把所有的back事件都发到js端,如果js端没监听,或者监听都返回了false,那么就会回到继承了DefaultHardwareBackBtnHandler接口,实现了invokeDefaultOnBackPressed的Activity处理。

推荐使用 AppCompatActivity implements DefaultHardwareBackBtnHandler这种方式集成。连接中也给了说法。

@Override
    public void invokeDefaultOnBackPressed() {
        ToastUtils.showShortToast("js默认返回结束调用执行Activity销毁");//重要
        super.onBackPressed();
    }
    @Override
    protected void onPause() {
        super.onPause();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostPause(this);
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostResume(this, this);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostDestroy(this);
        }
    }
    @Override
    public void onBackPressed() {

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed();
            ToastUtils.showShortToast("js返回");//重要
        } else {
            super.onBackPressed();//不会走这里
            ToastUtils.showShortToast("ceshi");
        }

    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

我都快哭了我..............................

18.
image.png

写成'/reactjs/js/news'会报错,要从根项目.开始

19.react-native-router-flux 根据原生的传值,跳转不同的界面
 render() {
        let title = this.props.title
        let tag_id = this.props.tag_id
        return<Router>
            <Scene key="root">
                <Scene key="home" component={News} title={title} />
                <Scene key="mine" component={Tab} initial={tag_id == "1" ? true : false}  title={title} message={title}/>
            </Scene>
        </Router>
    }

message是向tab组件传值过去,用this.props.message来获取

20.isMounted(...)is deprecated in plain JavaScript React classes解决方法
image.png

首先,出现此错误提示的原因是源代码内有已被React舍弃的代码,但此并不影响程序运行。
在index.js 内写入以下代码可屏蔽此提示。

import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);
21.webstrom上传代码到github

使用WebStorm/IDEA上传本地项目到GitHub
忽略文件

image.png

然后在进行提交
SSH Key若果有创建过就不用创建的。
在另外一台电脑上,拉取,然后,就可以两台电脑协同合作。

22. Cannot find module node_modules\react-native\local-cli\cli.js'

npm install ,然后:npm install重新安装以后,配置

npm config set registry https://registry.npm.taobao.org --global  
npm config set disturl https://npm.taobao.org/dist --global 
23.verbose stack SyntaxError: Unexpected end of JSON input while parsing near '...imer-mixin":"^0.13.2"'

从网络上拉去项目,报错,解决
npm -g i npm@4连接

24.Native module VectorIconsModule tried to override VectorIconsModule for module name RNVectorIconsModule. If this was your intention, set canOverrideExistingModule=true
image.png

找到MainApplication.java(android/app/src/main/java/com),里面有有重复的引用,把重复的部分删除就行了

25.React Native Undefined is not an object(evaluating ‘_react2.PropTypes.func’)

import React, { Component, PropTypes } from 'react';失效应该用下面的写法。

import React, { Component } from 'react';
import PropTypes from 'prop-types';
把PropTypes 从prop-types 中引入
26.使用react-native-swiper,从网络加载数据,圆点不滚动,停留在第一个。图片数量错乱
<Swiper
   key={this.state.image.length}
   style={styles.swiper}
>

添加key.参考资料

27 xx is invalid;it must be a function, usually from the 'prop-type' package,but received 'string'
image.png
28.在使用react-native-scrollable-tab-view+flatlist实现功能的时候,用了scrollview包裹了list,这让我犯了很大的错误。浪费了很多的时间
<ScrollableTabView tabBarBackgroundColor='#fff' //tab栏目背景色
                                       tabBarActiveTextColor='#cb1c23'//选中的文字颜色
                                       tabBarInactiveTextColor='#333'//为选中的文字颜色
                                       tabBarUnderlineStyle={styles.tabBarUnderline}
                                       tabBarTextStyle={styles.text_style}
                                       renderTabBar={()=><ScrollableTabBar />}>
                        {
                            this.state.new_tabs.map((item,index)=>{
                                return  <NewsList  type_id={item.id}  tabLabel={item.name} key={index} />
                            })
                        }
                    </ScrollableTabView>

上面是正确的写法。

29,react native使用mobx , can't find variable:Symbol

链接

  1. 把mobx降版本到 4.3.1 . mobx-react降版本到 5.1.0 即可.或者
  2. 在.babelrc配置文件 增加 ployfill插件 "babel-plugin-transform-runtime"即可
{
  "presets": [
    "react-native"
  ],
  "plugins": [
    "transform-decorators-legacy",
     "babel-plugin-transform-runtime"
  ]
}
30,There are multiple mobx instances active. This might lead to unexpected results
31.react native 删除第三方库,删干净那种。。。

链接
首先需要删除在RN的package.json中的依赖,输入一下命令:
npm uninstall --save react-native-video,
如果是组件作为devDependencies,需要加上-D,
如果是从optionalDependencies中删除,还需要加上-o的参数,
我为了保险能删干净,直接输入一下命令:
npm uninstall -s -D -O 组件名

32.npm 安装第三方库的指定的版本

npm install --save 库名@2.8.1
或者yarn add [package]@[version]

32 Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=512m; support was removed in 8.0

这个直接用webstrom运行android产生的,后面直接用了android studio来直接运行,就略过了这个问题,不在消耗时间来解决他了

33.第一次运行react-native start 提示throw er; // Unhandled 'error' event

原因端口被占了。
参考资料资料

image.png

34.react-native项目删除node_module文件夹,重新加载

yarn install

35 Debug模式下View config not found for name RCTView
image.png

不调试的时候,是可以运行的。
出现这种错误是因为在React 中,组件的名字必须是大写字母开头,

36.java.lang.RuntimeException: Tried to access a JS module before the React instance was fully set up. Calls to ReactContext#getJSModule should only happen once initialize() has been called on your native module.
37 Module AppRegistry is not a registered callable module(calling runApplication)

Module AppRegistry is not a registered callable module (calling runApplication)
原因:卸载了三方库,运行,但是此时出入热加载模式,注册重复,关闭热加载就行了
参考文章文章

38 解决React Native的Image组件中不更新图片的问题,采用base64显示

情景:使用百度云拍照识别数字返回给RN,每次携带的image_url都是一个地址,而rn中的image组件对相同的地址是有缓存的,所有拍照之后,一直都是显示的第一张,所以在android端把实际地址转成base64,传到RN,让RN读取base64的,就能实现啦
部分代码:
android中设置

public static String imageToBase64() {
        String path=Environment.getExternalStorageDirectory()+ "/shuiwu_pic/"+ "water.jpg";
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

获取base64字符串

 onScanningResult = (result) => {
        let baseImg=`data:image/png;base64,${result.image_url}`;
        this.setState({
            image_url:baseImg,
            real_num: result.result === "识别失败" ? "0" : result.result
        })

    }
。。。
 <Image source={{uri:this.state.image_url}}
                               style={styles.image}/>}
39, react-native 传base64到七牛
let xhr=new XMLHttpRequest();
               xhr.onreadystatechange=function()
               {
                   if(xhr.readyState===4&&xhr.status===200)
                   {
                       let  res=JSON.parse(xhr.responseText)
                       console.log("filekey"+res.key)
                       
                   }
               }
                xhr.open("post","http://upload.qiniup.com/putb64/-1/",true)
                xhr.setRequestHeader("Content-Type", "application/octet-stream");
                xhr.setRequestHeader("Authorization", "UpToken " + 你从服务器获取的token);
                xhr.send(this.state.image_base64)

40,react-native webview中图片以宽度自适应

 let reg=  new RegExp("<img", "g")
        return (
            <View style={styles.container}>
                <WebView
                 style={styles.webview}
                bounces={false}
                scalesPageToFit={true}
                 renderError={
                     ()=>{
                         return <ErrorPage/>
                     }
                 }
                source={{html: this.state.info.item.item.content.replace(reg,"<img style='max-width:100%;height:auto'")}}

                />
            </View>
        );

41.react-native android 打包 出现问题

image.png

删除自动生成的drawable目录下的文件
参考资料

42,react-native-router-flux 下点击android返回键2秒内推出
 return <Router
            backAndroidHandler={()=>{
                console.log(Actions.state)
                if(Actions.state.index===0) {
                    if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
                        //最近2秒内按过back键,可以退出应用。
                        // return false;
                        BackHandler.exitApp();//直接退出APP
                    }else{
                        this.lastBackPressed = Date.now();
                        ToastAndroid.show('再按一次退出应用', 1000);//提示
                        return true;
                    }
                }
            }}>
            <Scene key="root">
                <Scene key="login" component={LoginPage}  initialPage={true} hideNavBar={true} />
           </Scene>
</Router>

43,react-native 上传图片或者文件到七牛

1.上传base64位图片到七牛,核心代码

               var url = "http://upload.qiniup.com/putb64/-1/";
              var xhr = new XMLHttpRequest();
              xhr.open("post", url, true);
              xhr.setRequestHeader("Content-Type", "application/octet-stream");
              xhr.setRequestHeader("Authorization", "UpToken " + this.state.qiniu_token);
              xhr.send(pic);
              xhr.onreadystatechange = () => {
                  if (xhr.readyState === 4 && xhr.status === 200) {
                     //自己的逻辑
                      let res = JSON.parse(xhr.responseText)
                      let file_key = this.state.img_header + res.key
                      var img_arr = this.state.select_img_urls
                      img_arr.push({'url': file_key})
                      var img_keys = this.state.select_img_keys
                      img_keys.push(res.key)
                      this.setState({
                          select_img_urls: img_arr,
                          select_img_keys: img_keys,
                      })
                      EasyLoading.dismiss()
                      console.log('选取图片数组select_img_urls1', this.state.select_img_urls)
                      return file_key
                  } else {

                  }
              }

原生js方式上传文件[视频]到七牛,
参考文章:文章

 let realpath="file://"+path
        console.log("绝对路径",realpath)
        let names=path.split("/")
        let name_key=names[names.length-1]
        console.log("名称",name_key)
        let formData=new FormData()
        formData.append("file",{uri:realpath,type:"application/octet-stream",name:name_key})
        // formData.append("key",name_key),不设置,服务器会随机生成hash值
        formData.append("token",this.state.qiniu_token)
        let options={}
        options.body=formData
        options.method="POST"
        console.log("上传的参数",JSON.stringify(formData))
         fetch("http://upload.qiniup.com/",options)
            .then(response => response.json())
             .then(res=>{
                 console.log("成功",res)
                res.filename=name_key
             }).catch((e)=>{
                 console.log("异常",e.toString())
         })

注意:这样传到七牛,七牛返回的文件名是没有中文的,可以自己在拿到的结果中处理

44 warnOnce could not be found within the project

45 cli-platform-android/native_modules.gradle找不到指定的路径

androidstudio中直接删除

46 react-native webview与react-native通信

情景再现:webview中有多张图片,点击某张图片,就能查看大图。结合react-native-image-zoom-viewer库查看大图
在webview核心代码

render() {
        let reg=  new RegExp("<img", "g")

        let html_source=`<!DOCTYPE html>
              <html>
              <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
              <body>
              <button style="display: none" onClick="hhh(11)"  id="btn">点击</button>
              ${this.state.content.replace(reg,"<img style='max-width:100%;height:auto;width:100%'")}
               <script>
              
    (function hhh(text) {
        let hideButon=  document.getElementById('btn')
        let images= document.getElementsByTagName("img")
        hideButon.innerHTML=images.length;
        let imgarr=[]
        for (let i=0;i<images.length;i++){
            let url_img=images[i].src
            imgarr.push(url_img)
            images[i].onclick=function() {
              let data={"item":imgarr,"index":i}
             window.ReactNativeWebView.postMessage(JSON.stringify(data));
            }
            
           
        } 
    })(window)
</script>
              </body>
              
              </html>`
        const {imgs,index} = this.state
        let arr = []
        imgs.map((item) => {
            let dic = {url:item}
            arr.push(dic)
        })
        return (
            <View style={styles.container}>
                <WebView
                 style={styles.webview}
                 ref={webview => { this.webview = webview; } }
                bounces={false}
                scalesPageToFit={true}
                 renderError={
                     ()=>{
                         return <ErrorPage/>
                     }
                 }
                source={{html: html_source}}
                 onMessage={(e) => {
                     console.log("接收",e.nativeEvent.data)
                     let arr = JSON.parse(e.nativeEvent.data).item
                     let arr_index=JSON.parse(e.nativeEvent.data).index

                     this.setState({
                         imgs: arr,
                         index:arr_index,
                         is_show:true,
                     })

                 }}
                 startInLoadingState={true}
                />

                <Modal visible={this.state.is_show} transparent={true}>
                    <ImageViewer onClick={() => {
                        this.setState({
                            is_show:false
                        });
                    }} imageUrls={arr} index={index} />
                </Modal>
            </View>
        );
    }
}

function hhh是立即执行函数,使用<button style="display: none" onClick="hhh(11)" id="btn">点击</button>来绑定触发。
window.ReactNativeWebView.postMessage(JSON.stringify(data));来传递参数

 onMessage={(e) => {
                     console.log("接收",e.nativeEvent.data)
                     let arr = JSON.parse(e.nativeEvent.data).item
                     let arr_index=JSON.parse(e.nativeEvent.data).index

                     this.setState({
                         imgs: arr,
                         index:arr_index,
                         is_show:true,
                     })

                 }}

webview中接收参数
注意

 const {imgs,index} = this.state
        let arr = []
        imgs.map((item) => {
            let dic = {url:item}
            arr.push(dic)
        })

如果在model中直接使用this.state.imgs和this.state.index是访问不了的,有问题,所有使用上面的代码进行传递

47 React Native——嵌套WebView中的返回处理

连接感谢
情景再现,详情使用react-native-webview的控件的webview加载一个url.这个网页能一层一层的点击,但是返回的话,一下就整个界面就返回出去了,所以,。。。
核心代码

监听返回键
componentDidMount() {
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }
  //android自带返回键
  onBackAndroid = () => {
    if (this.state.backButtonEnabled) {
      this.webview.goBack();
      return true;
    } else {
      Actions.pop()
      return true;
    }
  }
componentWillUnmount(): void {
    if (Platform.OS === 'android') {
    this.listenter.remove()
    }
  }
自定义返回键
_left_button() {
    return <TouchableWithoutFeedback onPress={() => {
      if (this.state.backButtonEnabled) {
        this.webview.goBack();
        return true;
      } else {
        Actions.pop()
        return true;
      }
    }
    }><Image
        style={{width: Size(48), height: Size(48), marginLeft: Size(32),marginTop:ifIphoneXNavTitle() + Size(32) * 2,position:'absolute'}}
        source={require('../../../res/image/ic_left_arrows.png')}/></TouchableWithoutFeedback>;
  }

....

onNavigationStateChange = navState => {
    this.setState({
      backButtonEnabled: navState.canGoBack
    });
  };
....
 <WebView
                    ref={'webView'}

                    source={{uri: this.state.url}}  //此处URL为服务器返回的html
                    ref={webview => { this.webview = webview; } }
                    javaScriptEnabled={true}
                    // onLoadEnd={this.pageOnLoaded.bind(this)}
                    onNavigationStateChange={this.onNavigationStateChange}
                    />

注意:需要解绑,别忘了,不然退出不了app,

48 viewpagerAndroid is error in the reactnative0.61

1.yarn add @react-native-community/viewpager

  1. react-native link @react-native-community/viewpager
  2. 在源码中
    react-native-scrollable-tab-view/index.js
    const ViewPagerAndroid = require('@react-native-community/viewpager')

49 node_modules\realpath-native\index.js: Modulefs` does not exist in the Haste module map

把index.js文件内容全部注释

50 react-native-scrollable-tab-view 横向切换时点击事件会触发,进入二级界面问题。

不使用RN的 TouchableWithoutFeedback等点击,使用 import {TouchableWithoutFeedback} from 'react-native-gesture-handler'
注意在:在android的MainActivity中增加

import { TouchableNativeFeedback, TouchableHighlight, TouchableOpacity, TouchableWithoutFeedback } from 'react-native-gesture-handler' 点击没效果,android 中MainActivity中增加

import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
...
 @Override
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName()) {
      @Override
      protected ReactRootView createRootView() {
        return new RNGestureHandlerEnabledRootView(MainActivity.this);
      }
    };
  }

就ok了

51 android fetch request failed

https://github.com/facebook/react-native/issues/28551

image.png

let formdata=new FormData()
                let file={uri:response.uri,type:"multipart/form-data",name:"image.jpg"}
                formdata.append("image",file)
                fetch(urls.file_update,{
                    method:"POST",
                    headers: {
                        'Content-Type': 'multipart/form-data;charset=utf-8',
                        "accept": "application/json",
                        "token": this.state.token,
                        "staff": this.state.staff_id,
                    },
                    body:formdata,
                }).then((response) => response.json())
                    .then(res=>{
                        console.log("数据",res)
                    }).catch(e=>{
                    console.log("异常",e.toString())
                })

react-native 上传图片详解
封装过的:

 let formdata={
                    "image":{uri:response.uri,type:"multipart/form-data",name:"image.jpg"}
                }

                HttpUtils.fetch_request(urls.file_update,"post",formdata).then(res=>{
                    console.log("数据",res)
                }).catch(e=>{
                    console.log("异常",e.toString())
                })

使用rn-fetch-blob上传图片

RNFetchBlob.fetch("POST", urls.file_update,
                    {
                        "token": this.state.token,
                        "staff": this.state.staff_id.toString(),
                        'Content-Type': 'multipart/form-data'
                    }, [
                        {name: "image", filename: filename, type: "image/jpg", data: RNFetchBlob.wrap(fileuri)}
                    ]
                ).then(response => response.json())
                    .then(res => {
                       
                        console.log("成功", res)
                    }).catch(e => {
                    console.log("异常", e.toString())
                })

注意:body ,参数是以数组形式添加,name:就是传递的参数名称
react-native 实现上传功能

52 关于react 父级组件更新数据触发子组件更新渲染问题

image.png

感谢https://www.jianshu.com/p/7049b035766b

53 VSCode yarn : 无法加载文件 C:\Users\Administrator\AppData\Roaming\npm\yarn.ps1,因为在此系统上禁止运行脚本。

set-ExecutionPolicy RemoteSigned不是内部命令,不是在cmd中使用哦,要打开windows powershell
shift+鼠标右键在当前文件夹打开windows powersshell,切换到管理员 Start-Process powershell -Verb runAs
以管理员身份执行set-ExecutionPolicy RemoteSigned

image.png

54 使用ant-design/react-native,手机端组件

yarn add @ant-design/react-native babel-plugin-import @react-native-community/viewpager @ant-design/icons-react-native
并新建 .babelrc文件 ,

{
    "plugins": [
      ["import", { libraryName: "@ant-design/react-native" }] // 与 Web 平台的区别是不需要设置 style
    ]
}

上面第二组件是按需加载,第三个是使用到tabs,android端需要的。

55ant design mobile图标不显示问题

image.png

yarn add @ant-design/react-native 注意:拷贝到android\app\src\main\assets\fonts文件夹下哦,

56 react-native 修改端口号,亲测可用

找到根目录 metro.config.js


module.exports = {
  //新增
  server: {
    port: 8083,
  },
};

注意:保存代码之后在运行下 android原生项目

react-native修改端口号

57 react-native-map3d地图,

天地图坐标转成高德地图坐标,在react-native-map3d上展示
参考链接

const pi = 3.14159265358979324;
const a = 6378245.0;
const ee = 0.00669342162296594323;
//注意在参考链接中,参数位置是写反了得
 outOfChina(lat, lon)
    {
        if ((lon < 72.004 || lon > 137.8347)&&(lat < 0.8293 || lat > 55.8271)){
            console.log("在国外")
            return true;
        }else {
            console.log("在国内")
            return false;
        }
    }
     transformLat(x,y)
    {
        let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
        return ret;
    }

     transformLon(x,y)
    {
        let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
        return ret;
    }

     transform(wgLat,wgLon)
    {
        console.log("经纬度",wgLat)
        console.log("we",wgLon)
        let mars_point={lon:0,lat:0};
        if (this.outOfChina(wgLat, wgLon))
        {
            mars_point.lat = wgLat;
            mars_point.lon = wgLon;
            return ;
        }
        console.log("经纬度",typeof  wgLat)
        let dLat = this.transformLat(wgLon - 105.0, wgLat - 35.0);
        let dLon = this.transformLon(wgLon - 105.0, wgLat - 35.0);
        let radLat = wgLat / 180.0 * pi;
        let magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        let sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
        mars_point.lat = wgLat + dLat;
        mars_point.lon = wgLon + dLon;
        return mars_point
    }

调用transformLat

高德地图坐标转天地图坐标

const pi = 3.14159265358979324;
transformGCJ2WGS(gcjLat, gcjLon) {
        let d =this.delta(gcjLat, gcjLon)
        return {
            'lat': gcjLat - d.lat,
            'lon': gcjLon - d.lon
        }
    }

    delta(lat, lon) {
        let a = 6378245.0 //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
        let ee = 0.00669342162296594323 //  ee: 椭球的偏心率。
        let dLat = this.transformLat(lon - 105.0, lat - 35.0)
        let dLon = this.transformLon(lon - 105.0, lat - 35.0)
        let radLat = lat / 180.0 * 3.14159265358979324
        let magic = Math.sin(radLat)
        magic = 1 - ee * magic * magic
        let sqrtMagic = Math.sqrt(magic)
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI)
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI)
        return {
            'lat': dLat,
            'lon': dLon
        }
    }
     transformLat(x, y) {
        let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x))
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0
        ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0
        ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0
        return ret
    }
     transformLon(x, y) {
        let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x))
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0
        ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0
        ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0
        return ret
    }

58.去掉黄色警告

console.ignoredYellowBox = ['Warning: BackAndroid is deprecated. Please use BackHandler instead.','source.uri should not be an empty string','Invalid props.style key'];
console.disableYellowBox = true //
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容