react native xunwoo编程技巧

React Native 版本执行0.57的规则

鄙弃旧的if判断

{this.state.listArr.length > 0 &&
                    <View style={styles.teamHeader}>
                        <Image
                            source={this.state.adminInfo.weixin_image ? { uri: this.state.adminInfo.weixin_image } : require('../../images/user.png')}
                            style={{ width: Px2dp(32), height: Px2dp(32), backgroundColor: "#ccc", borderRadius: Px2dp(16), marginRight: Px2dp(15) }}
                        />
                        <View style={{ flexDirection: "row", flex: 1, alignItems: "center" }}>
                            <Text style={styles.teamHeaderTel}>{this.state.adminInfo.phone}</Text>
                        </View>
                        <Text style={styles.teamHeaderTxt}>创建者</Text>
                    </View>
                }Ï

标准的FlatList

<FlatList
                    style={styles.flatListStyle}// 样式
                    data={this.state.listArr}// 数据源
                    initialNumToRenƒder={10}// 
                    keyExtractor={(item, index) => index.toString()}
                    ListFooterComponent={() => {
                        return (<LoadingMore dataFlag={this.state.dataFlag} dataLength={this.state.listArr.length} />)
                    }}//尾部组件
                    renderItem={({ item }) => this.renderItem(item)}// 渲染
                    onRefresh={() => {
                        this.setState({
                            listArr: [],
                            pageNum: 1,
                        })
                        this.memberList(1);
                    }}//头部刷新组件
                    ItemSeparatorComponent={() => {
                        return (
                            <View style={{
                                borderBottomWidth: Pixel,
                                borderBottomColor: Colors.borderColor
                            }}></View>
                        )
                    }}// 分割线
                    refreshing={this.state.isLoading}//加载图标
                    onEndReached={() => this.onEndReached()} // 加载更多
                    onEndReachedThreshold={.1}// 加载更多触发时机
                    ListEmptyComponent={() => {
                        // 无数据时显示的内容
                        return (
                            !this.state.dataFlag && this.state.listArr.length <= 0 ?
                                <View style={styles.noDataBox}>
                                    <Image source={require("../../images/on_team.png")} />
                                    <Text style={styles.noDataText}>暂无家庭成员</Text>
                                </View>
                                : null
                        )
                    }}
                />

Modal弹出层、TextInput

<Modal
                    visible={this.state.visibleFlag}
                    animationType='fade'
                    onRequestClose={() => { this.setState({ visibleFlag: false }) }}
                    transparent={true}>
                    <TouchableOpacity
                        activeOpacity={.8}
                        onPress={() => {
                            this.setState({
                                visibleFlag: false,
                            })
                        }}
                        style={styles.shadeModo}>

                        <TouchableOpacity
                            onPress={() => { }}
                            activeOpacity={1}
                        >
                            <View style={styles.content}>
                                <Text style={styles.contentTit}>邀请家庭成员</Text>
                                <TextInput
                                    style={styles.input}
                                    returnKeyType={"done"}// 键盘确定按钮类型 done/go/next/search/send
                                    placeholderTextColor="#999"
                                    keyboardType="numeric"
                                    placeholder="请输入被邀请人手机号"
                                    autoFocus={true}
                                    maxLength={11}
                                    underlineColorAndroid={'transparent'}
                                    defaultValue={this.state.phone}
                                    onChangeText={(text) =>
                                        this.setState({
                                            phone: text
                                        })
                                    }
                                />
                                <View style={styles.contentFooter}>
                                    <TouchableOpacity activeOpacity={0.8} style={styles.offBtn} onPress={() => {
                                        this.setState({
                                            visibleFlag: false,
                                        })
                                    }}>
                                        <Text style={styles.offBtnTxt}>取消</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity activeOpacity={0.8} style={styles.onBtn} onPress={() => {
                                        this.setState({
                                            visibleFlag: false,
                                        })
                                        this.save();
                                    }}>
                                        <Text style={styles.onBtnTxt}>确定</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </TouchableOpacity>
                </Modal>

//
shadeModo: {
        width: SCREEN_WIDTH,
        height: SCREEN_HEIGHT,
        backgroundColor: Colors.maskColor,
        justifyContent: 'center',
        alignItems: 'center'
    },
    content: {
        width: Px2dp(250),
        height: Px2dp(182),
        backgroundColor: 'white',
        alignItems: 'center',
        borderRadius: Px2dp(6),
    },

传入页码的写法、也有不需要页码的接口

memberList(pageNum) {
        if (pageNum == 1) {
            this.setState({
                isLoading: true,
                dataFlag: true,
                listArr: [],
            })
        }
        Fetch(requestUrl.memberList, {
            "userId": UserInfo.id,
            "pageNo": pageNum.toString(), //1
            "pageSize": this.state.pageSize.toString(), //10
        }).then(data => {
            console.log(data)
            if (data.status == "SUCCESS" && data.data.userInfo) {
                if (data.data.memberList.length >= this.state.pageSize) {
                    let tempArr = this.state.listArr;
                    tempArr = tempArr.concat(data.data.memberList);
                    this.setState({
                        dataFlag: true,
                        isLoading: false,
                        listArr: tempArr,
                        adminInfo: data.data.userInfo,
                    })
                } else {
                    let tempArr = this.state.listArr;
                    tempArr = tempArr.concat(data.data.memberList);
                    this.setState({
                        dataFlag: false,
                        isLoading: false,
                        listArr: tempArr,
                        adminInfo: data.data.userInfo,
                    })
                }
            } else {
                this.setState({
                    isLoading: false,
                    dataFlag: false,
                })
            }
        }).catch((error) => {
            console.log('接口请求错误信息', error);
        })
    }

声明对象,定义默认避免引用原生js判断是否为空的尴尬

 selectFile: { id: '' },// 选中的文件夹
 <Text style=
 {[styles.groupItemTitle, this.state.selectFile.id == "" ? { color: 'red' }
  : null]}>默认文件夹(全部标签)</Text>

上传图片与没有图片的提交方式

/** 
     * saveArticle 创建/修改物品
     * 
     * id 空 创建
     * id 真 修改
     * 
     * images 多个url逗号隔开
     * 
     * */
    saveArticle() {
        if (!this.state.label_code) {
            Toast({ "text": "请输入标签编码" })
        } else if (!this.state.article_name) {
            Toast({ "text": "请输入标签名称" })
        } else if (!this.state.head_portrait) {
            Toast({ "text": "请上传头像" })
        } else {
            let imgArr = this.state.imgArr;
            let _this = this;
            // // 创建图片路径
            // let _time = parseInt(new Date().getTime());
            // let suiji = Math.floor(Math.random() * 1000)
            // let year = new Date().getFullYear();
            // let month = new Date().getMonth() + 1;
            // let day = new Date().getDate();
            // let path = year + '/' + month + '/' + day + '/' + _time + suiji + this.state.head_portrait.substr(this.state.head_portrait.lastIndexOf("."));
            // let formData = new FormData();
            // formData.append("file", { uri: IOS ? "file://" + this.state.head_portrait : this.state.head_portrait, type: 'application/octet-stream', name: path });
            // Fetch(requestUrl.uptoken, { 'key': path }).then(data => {
            //     formData.append("key", path);
            //     formData.append("token", data.data);
            //     fetch("https://upload.qiniup.com", {
            //         method: 'POST',
            //         headers: {},
            //         body: formData,
            //         contentType: false,
            //         processData: false,
            //     }).then((response) => response.json())
            //         .then((responseData) => {
            //             console.log(responseData)
            //             if (responseData.key) {
            //                 _this.setState({
            //                     head_portrait_url: ImgUrl + responseData.key,
            //                 });
            //             } else {
            //                 Toast({ "text": "图片上传失败" })
            //             }
            //         })
            //         .catch((error) => {
            //             console.log('error', error);
            //         });
            // })

            if (imgArr.length > 0) {
                for (let i = 0; i < imgArr.length; i++) {
                    // 创建图片路径
                    let _time = parseInt(new Date().getTime());
                    let suiji = Math.floor(Math.random() * 1000)
                    let year = new Date().getFullYear();
                    let month = new Date().getMonth() + 1;
                    let day = new Date().getDate();
                    let path = year + '/' + month + '/' + day + '/' + _time + suiji + imgArr[i].path.substr(imgArr[i].path.lastIndexOf("."));
                    let formData = new FormData();
                    formData.append("file", { uri: IOS ? "file://" + imgArr[i].path : imgArr[i].path, type: 'application/octet-stream', name: path });
                    Fetch(requestUrl.uptoken, { 'key': path }).then(data => {
                        formData.append("key", path);
                        formData.append("token", data.data);
                        fetch("https://upload.qiniup.com", {
                            method: 'POST',
                            headers: {},
                            body: formData,
                            contentType: false,
                            processData: false,
                        }).then((response) => response.json())
                            .then((responseData) => {
                                if (responseData.key) {
                                    let temp = _this.state.imgUrlArr;
                                    temp.push(ImgUrl + responseData.key);
                                    _this.setState({
                                        imgUrlArr: temp,
                                    });
                                    if (temp.length >= imgArr.length && this.state.head_portrait_url) {
                                        Fetch(requestUrl.saveArticle, {
                                            "article_id": _this.state.article_id,// 物品id
                                            "user_id": UserInfo.id,
                                            "label_code": _this.state.label_code,
                                            "article_name": _this.state.article_name,
                                            "head_portrait": _this.state.head_portrait_url,
                                            "remarks": _this.state.remarks,
                                            "belong_folder": _this.state.fileId,
                                            "longitude": _this.state.longitude,
                                            "latitude": _this.state.latitude,
                                            "binding_time": "",
                                            "images": _this.state.imgUrlArr.join(","),//备注图片,
                                            "address": _this.state.address,// 位置信息
                                        }).then(data => {
                                            console.log(data)
                                            if (data.status == "SUCCESS") {
                                                Toast({ "text": "修改成功" })
                                                this.setState({
                                                    editFlag: false,
                                                })
                                            } else {
                                                Toast({ "text": "修改失败" })
                                            }
                                        }).catch((error) => {
                                            console.log('接口请求错误信息', error);
                                        })
                                    }
                                } else {
                                    Toast({ "text": "图片上传失败" })
                                }
                            })
                            .catch((error) => {
                                console.log('error', error);
                            });
                    })
                }
            } else {
                Fetch(requestUrl.saveArticle, {
                    "article_id": _this.state.article_id,// 物品id
                    "user_id": UserInfo.id,
                    "label_code": _this.state.label_code,
                    "article_name": _this.state.article_name,
                    "head_portrait": _this.state.head_portrait_url,
                    "remarks": _this.state.remarks,
                    "belong_folder": _this.state.fileId,
                    "longitude": _this.state.longitude,
                    "latitude": _this.state.latitude,
                    "binding_time": "",
                    "images": _this.state.imgUrlArr.length > 0 ? _this.state.imgUrlArr.join(",") : '',//备注图片
                    "address": _this.state.address,// 位置信息
                }).then(data => {
                    console.log(data)
                    if (data.status == "SUCCESS") {
                        if (data.status == "SUCCESS") {
                            Toast({ "text": "修改成功" })
                            this.setState({
                                editFlag: false,
                            })
                        } else {
                            Toast({ "text": "修改失败" })
                        }
                    } else {
                        Toast({ "text": "修改失败" })
                    }
                }).catch((error) => {
                    console.log('接口请求错误信息', error);
                })
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值