RNReactNativeRN

React native开发中遇到的坑

2018-04-24  本文已影响604人  蒲小帅丶
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-dev 库名@2.8.1

上一篇 下一篇

猜你喜欢

热点阅读