为什么react-native-material-dropdown在我用它来编辑和添加专业的方式上如此之慢?

时间:2018-02-23 09:01:57

标签: performance react-native dropdown

我的应用程序下拉菜单非常慢。如果我进入设置屏幕并尝试更改我的专业,这需要很长时间。或者在此特定屏幕中添加或编辑专业的任何事情。我真的需要更快地添加或编辑专业。我不确定编辑或添加专业的原因是否需要太长时间。而且我不确定如何更快地添加和编辑专业。所以我发布了整个组件,我正在评论处理添加或编辑专业的部分。我正在使用react-native-material-dropdown。 这是整个组件代码:

import React from 'react';
import PropTypes from 'prop-types';
import { View, ScrollView, Text, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import { compose, withStateHandlers } from 'recompose';
import { Dropdown } from 'react-native-material-dropdown';
import { Icon } from 'react-native-material-ui';
import R from 'ramda';
import { ConnectivityRenderer } from 'react-native-offline';
import NetworkConnectivity from '../error/NetworkConnectivity';
import { toArray } from '../selectors';
import { Container, Switch, SwitchOption } from './common';
import { editStudent } from '../actions';

const propTypes = {
  toolbar: PropTypes.elem,
  loading: PropTypes.bool,
  university: PropTypes.shape({
  id: PropTypes.string,
  name: PropTypes.string,
  }),
  universities: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string,
      name: PropTypes.string,
    })
  ),
  degrees: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string,
      name: PropTypes.string,
    })
  ),
  studentDegrees: PropTypes.arrayOf(
    PropTypes.shape({
      index: PropTypes.number,
      track: PropTypes.string,
    })
  ),
  errors: PropTypes.shape({
    university: PropTypes.string,
    degree: PropTypes.string,
  }),
  year: PropTypes.string,
  onUniversityChange: PropTypes.func,
  onTermChange: PropTypes.func,
  onDegreeChange: PropTypes.func,
  onYearChange: PropTypes.func,
  onTrackChange: PropTypes.func,
  onAddDegree: PropTypes.func,
  onDone: PropTypes.func,
};

const contextTypes = {
  uiTheme: PropTypes.object.isRequired,
};

const validate = state => {
  const result = {};

  if (!state.university.id) {
    result.university = 'You should select an university';
  }

  return result;
};

const enhance = compose(
  connect(
    ({ user, universities, degrees }) => ({
      studentId: user.id,
      user,
      universities: toArray(universities),
      degrees: toArray(degrees),
    }),
    { editStudent }
  ),
  withStateHandlers(
    props => {
      return {
        university: props.user.university || {},
        year: props.user.academicClass || 'freshman',
        studentDegrees: R.isEmpty(props.degrees)
          ? []
          : R.isEmpty(props.user.studentDegrees)
            ? [{ degree_id: props.degrees[0].id, track: 'Major' }]
            : R.values(props.user.studentDegrees),
        errors: {},
       };
    },
    {
      onUniversityChange: () => (value, index, data) => ({
        university: data[index],
       }),
      onYearChange: () => year => ({ year }),
      onTrackChange: state => ({ idx, track }) => ({
        studentDegrees: R.update(
          idx,
          R.assoc('track', track, state.studentDegrees[idx]),
          state.studentDegrees
        ),
      }),



      // Fucntion dealing with degree change

      onDegreeChange: (state, props) => ({ idx, index }) => ({
         studentDegrees: R.update(
          idx,
          R.assoc(
            'degree_id',
            props.degrees[index].id,
            state.studentDegrees[idx]
          ),
          state.studentDegrees
        ),
      }),


    // Function dealing with degree adding

    onAddDegree: (state, props) => () => ({
        studentDegrees: R.append(
          {
            degree_id: props.degrees[0].id,
            track: 'Major',
          },
          state.studentDegrees
        ),
      }),
      onRemoveDegree: state => idx => ({
        studentDegrees: [
          ...state.studentDegrees.slice(0, idx),
          ...state.studentDegrees.slice(idx + 1),
        ],
      }),


      // When the user is done with settings.
      // This function communicates with the back end to save things in the remote database
      onDone: (state, { studentId, editStudent }) => () => {
      const errors = validate(state);
        if (Object.keys(errors).length !== 0) {
          return { errors };
        }

        editStudent(
          studentId,
          state.year,
          state.university.id,
          state.studentDegrees
        );
      },
    }
  )
);




// The Settings Component 
  const FormUserSettings = (props, context) => {
  const styles = getStyles(props, context);

  return (
    <ConnectivityRenderer>
      {isConnected => (
        isConnected ? (
          <Container>
            {React.cloneElement(props.toolbar, {
              onRightElementPress: props.onDone,
            })}
            <ScrollView style={styles.container}>
              <Text
                style={[
                  styles.title,
                  props.errors.university ? styles.titleError : {},
                ]}
              >
                University
              </Text>

          // Selecting a university
              <Dropdown
                label="Select university..."
                data={props.universities.map(u => ({ id: u.id, value: u.name }))}
                onChangeText={props.onUniversityChange}
                value={props.university.name}
              />
              {props.errors.university &&
                <Text style={styles.errorMessage}>
                  {props.errors.university}
                </Text>}
              <View style={{ height: 16 }} />
                <Text style={styles.title}>Current Year</Text>
               <View style={{ height: 8 }} />
              <Switch
                value={props.year}
                onChange={props.onYearChange}
                selectedColor={styles.switchSelectedColor}
                unselectedColor={styles.switchUnselectedColor}
               >
                <SwitchOption text="Freshman" value="freshman" />
                <SwitchOption text="Sophomore" value="sophomore" />
                <SwitchOption text="Junior" value="junior" />
                <SwitchOption text="Senior" value="senior" />
                </Switch>
               <View style={{ height: 16 }} />
               <Text
                style={[styles.title, props.errors.degree ? styles.titleError : {}]}
              >
            Major / Minors
          </Text>
          {!R.isEmpty(props.degrees) &&
            props.studentDegrees.map((sd, idx) => {
              const degree = R.find(R.propEq('id', sd.degree_id), props.degrees);

              return (
                <View
                  key={`sd-${idx}`}
                  style={{ flex: 1, height: 96, marginTop: 24 }}
                >
                  <View
                    style={{
                      flex: 1,
                      flexDirection: 'row',
                      alignItems: 'flex-end',
                    }}
                  >
                    <View style={{ flex: 1 }}>
                      <Dropdown
                        style={{ flex: 1 }}
                        label="Select degree..."
                        data={props.degrees.map(d => ({
                          id: d.id,
                          value: d.name,
                        }))}
                        onChangeText={(value, index) =>
                          props.onDegreeChange({ idx, index })}
                        value={degree ? degree.name : ''}
                      />
                    </View>
                    {props.studentDegrees.length !== 1 &&
                      <TouchableOpacity
                        style={{ marginBottom: 8, paddingLeft: 24 }}
                        onPress={() => props.onRemoveDegree(idx)}
                      >
                        <Icon name="delete" size={24} />
                      </TouchableOpacity>}
                  </View>
                  <Switch
                    value={sd.track}
                    onChange={track => props.onTrackChange({ idx, track })}
                    selectedColor={styles.switchSelectedColor}
                    unselectedColor={styles.switchUnselectedColor}
                  >
                    <SwitchOption text="Major" value="Major" />
                    <SwitchOption text="Minor" value="Minor" />
                    <SwitchOption text="Certificate" value="Cert" />
                  </Switch>
                </View>
              );
            })}
          <TouchableOpacity style={{ padding: 10 }} onPress={props.onAddDegree}>
            <Text style={styles.addDegreeText}>+ Degree</Text>
          </TouchableOpacity>
        </ScrollView>
      </Container>
    ) : (
      <Container>
        {React.cloneElement(props.toolbar, {
          onRightElementPress: props.onDone,
        })}
        <NetworkConnectivity />
        <ScrollView style={styles.container}>
          <Text
            style={[
              styles.titleDisabled,
              props.errors.university ? styles.titleError : {},
            ]}
          >
            University
          </Text>
          <Dropdown
            label=""
            data={props.universities.map(u => ({ id: u.id, value: u.name }))}
            onChangeText={props.onUniversityChange}
            value={props.university.name}
            disabled={true}
            editable={false}
          />
          {props.errors.university &&
            <Text style={styles.errorMessage}>
              {props.errors.university}
            </Text>}
          <View style={{ height: 16 }} />
          <Text style={styles.titleDisabled}>Current Year</Text>
          <View style={{ height: 8 }} />
          <Switch
            value={props.year}
            onChange={props.onYearChange}
            selectedColor={styles.disabledSwitchSelectedColor}
            unselectedColor={styles.switchUnselectedColor}
          >
            <SwitchOption text="Freshman" value="freshman" />
            <SwitchOption text="Sophomore" value="sophomore" />
            <SwitchOption text="Junior" value="junior" />
            <SwitchOption text="Senior" value="senior" />
          </Switch>
          <View style={{ height: 16 }} />
          <Text
            style={[styles.titleDisabled, props.errors.degree ? styles.titleError : {}]}
          >
            Major / Minors
          </Text>

          // The problem of slowness starts here
          // I feel like something here should be improved
          {!R.isEmpty(props.degrees) &&
            props.studentDegrees.map((sd, idx) => {
              const degree = R.find(R.propEq('id', sd.degree_id), props.degrees);

                  return (
                    <View
                      key={`sd-${idx}`}
                      style={{ flex: 1, height: 96, marginTop: 24 }}
                    >
                      <View
                        style={{
                          flex: 1,
                          flexDirection: 'row',
                          alignItems: 'flex-end',
                        }}
                      >
                        <View style={{ flex: 1 }}>
                          <Dropdown
                            style={{ flex: 1 }}
                            label="Select degree..."
                            data={props.degrees.map(d => ({
                              id: d.id,
                              value: d.name,
                            }))}
                            disabled={true}
                            editable={false}
                            onChangeText={(value, index) =>
                              props.onDegreeChange({ idx, index })}
                            value={degree ? degree.name : ''}
                          />
                        </View>
                      </View>
                      <Switch
                        value={sd.track}
                         onChange={track => props.onTrackChange({ idx, track })}
                        selectedColor={styles.disabledSwitchSelectedColor}
                        unselectedColor={styles.switchUnselectedColor}
                      >
                        <SwitchOption text="Major" value="Major" />
                        <SwitchOption text="Minor" value="Minor" />
                        <SwitchOption text="Certificate" value="Cert" />
                      </Switch>
                    </View>
                  );
                })}
              <TouchableOpacity disabled={true} style={{ padding: 10 }} onPress={props.onAddDegree} disabled={true}>
                <Text style={styles.addDegreeTextDisabled}>+ Degree</Text>
              </TouchableOpacity>
            </ScrollView>
          </Container>
        )
      )}
    </ConnectivityRenderer>
  );
};



FormUserSettings.contextTypes = contextTypes;
FormUserSettings.propTypes = propTypes;

export default enhance(FormUserSettings);

0 个答案:

没有答案