category组件没有走compoenntDidMount生命周期导致isEdit is undefined?

来源:10-7 新增类别和删除类别(1)

mid_one

2020-08-15

图片描述
加载category组件的时候constructor和componentWillMount render都可以拿到isEdit:false, 但是componentDidMount却没有打印东西,经过测试我发现category组件加载的时候一直没有运行compoenntDidMount生命周期, 这里不知道为什么。麻烦老师给看看

import React from 'react';
import {View, Text, StyleSheet, ScrollView} from 'react-native';
import {connect, ConnectedProps} from 'react-redux';
import {DragSortableView} from 'react-native-drag-sort';
import _ from 'lodash';
import {RootState} from '@/models/index';
import {ICategory} from '@/models/category';
import Item, {parentWidth, itemWidth, itemHeight, margin} from './item';
import {RootStackNavigation} from '@/navigator/index';
import HeaderRightBtn from './headerightBtn';
import Touchable from '@/components/Touchable';

const mapStateToProps = ({category}: RootState) => {
  return {
    myCategorys: category.myCategorys,
    categorys: category.categorys,
    isEdit: category.isEdit,
  };
};

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {
  navigation: RootStackNavigation;
}

interface IState {
  myCategorys: ICategory[];
}

const fixedItems = [0, 1];

class Category extends React.Component<IProps, IState> {
  state = {
    myCategorys: this.props.myCategorys,
  };
  componentWillUnMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'category/setState',
      payload: {
        isEdit: false,
      },
    });
  }
  onSubmit() {
    const {dispatch, navigation, isEdit} = this.props;
    const {myCategorys} = this.state;
    dispatch({
      type: 'category/toggle',
      payload: {
        myCategorys,
      },
    });
    if (isEdit) {
      navigation.goBack();
    }
  }
  constructor(props: IProps) {
    super(props);
    props.navigation.setOptions({
      headerRight: () => {
        return <HeaderRightBtn onSubmit={this.onSubmit} />;
      },
    });
  }
  // componentDidMount() {
  //   const {navigation} = this.props;
  //   navigation.setOptions({
  //     headerRight: () => {
  //       return <HeaderRightBtn onSubmit={this.onSubmit} />;
  //     },
  //   });
  // }
  onLongPress() {
    const {dispatch} = this.props;
    dispatch({
      type: 'category/setState',
      payload: {
        isEdit: true,
      },
    });
  }
  onPress(item: ICategory, index: number, selected: boolean) {
    const {isEdit} = this.props;
    const {myCategorys} = this.state;
    const disabled = fixedItems.indexOf(index) > -1;
    if (disabled) return;
    if (isEdit) {
      if (selected) {
        this.setState({
          myCategorys: myCategorys.filter(
            (selectedItem) => selectedItem.id !== item.id,
          ),
        });
      } else {
        this.setState({
          myCategorys: myCategorys.concat(item),
        });
      }
    }
  }
  renderItem(item: ICategory, index: number) {
    const {isEdit} = this.props;
    const disabled = fixedItems.indexOf(index) > -1;
    return (
      <Item
        disabled={disabled}
        key={item.id}
        data={item}
        isEdit={isEdit}
        selected
      />
    );
  }
  renderUnSelectedItem(item: ICategory, index: number) {
    const {isEdit} = this.props;
    return (
      <Touchable
        key={item.id}
        onPress={() => this.onPress(item, index, false)}
        onLongPress={this.onLongPress}>
        <Item data={item} isEdit={isEdit} selected={false} />;
      </Touchable>
    );
  }
  onDataChange(data: ICategory[]) {
    this.setState({
      myCategorys: data,
    });
  }
  onClick(data: ICategory[], item: ICategory) {
    this.onPress(item, data.indexOf(item), true);
  }
  render() {
    const {categorys, isEdit} = this.props;
    const {myCategorys} = this.state;
    const classifyGroup = _.groupBy(categorys, (item) => item.classify);
    return (
      <ScrollView style={styles.container}>
        <Text style={styles.classifyName}>我的分类</Text>
        <View style={styles.classifyView}>
          <DragSortableView
            dataSource={myCategorys}
            renderItem={this.renderItem}
            sortable={isEdit}
            fixedItems={fixedItems}
            keyExtractor={(item) => item.id}
            onDataChange={this.onDataChange}
            parentWidth={parentWidth}
            childrenWidth={itemWidth}
            childrenHeight={itemHeight}
            marginChildrenTop={margin}
            onClickItem={this.onClick}
          />
          {/* {myCategorys.map(this.renderItem)} */}
        </View>
        <View>
          {Object.keys(classifyGroup).map((classify) => {
            return (
              <View key={classify}>
                <Text style={styles.classifyName}>{classify}</Text>
                <View style={styles.classifyView}>
                  {classifyGroup[classify].map((item, index) => {
                    if (
                      myCategorys.find(
                        (selectedItem) => selectedItem.id === item.id,
                      )
                    ) {
                      return null;
                    }
                    return this.renderUnSelectedItem(item, index);
                  })}
                </View>
              </View>
            );
          })}
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f3f6f6',
  },
  classifyName: {
    fontSize: 16,
    marginTop: 14,
    marginBottom: 8,
    marginLeft: 10,
  },
  classifyView: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: 5,
  },
});

export default connector(Category);

写回答

1回答

今朝

2020-08-15

报错了自然不走componentDidMount

0
5
今朝
你的函数写的有问题,类组件中除了react自带的生命周期函数可以取到this,其他的函数想要取到this需要自己绑定,一般用箭头函数即可
2020-08-15
共5条回复

跨平台应用ReactNative+TypeScript仿喜马拉雅开发App

从入门到实战,掌握用TypeScript开发ReactNative应用

832 学习 · 339 问题

查看课程