Текст не отображается после перерисовки - PullRequest
0 голосов
/ 08 сентября 2018

В приведенном ниже коде я запускаю компонент, который получит реквизиты, чтобы убедиться, что я передаю его в статусе сотрудника. После того, как я убедился, что сотрудник больше не является нулевым, я хочу показать его информацию, но он не отображается. Я console.logged "сделал это", чтобы увидеть, будет ли он регистрировать, когда сотрудник полностью загружен и перешел в состояние, и журнал выглядел просто отлично. Так почему же мой текст не отображается, когда console.log действительно запущен? (Данные извлекаются из firebase, поэтому я использую компонент, который получит реквизиты)

import React from 'react';
import { Text, TouchableWithoutFeedback, LayoutAnimation, NativeModules, View, } from 'react-native';
import { CardSection } from './common/index';
import { connect } from 'react-redux';
import { onPress } from '../actions/index';
const { UIManager } = NativeModules

UIManager.setLayoutAnimationEnabledExperimental && 
UIManager.setLayoutAnimationEnabledExperimental(true)

class FlatListItem extends React.Component {
  state = {
    show:false,
    employee:null
  }

  componentWillReceiveProps (nextProps) {
    this.setState({employee:nextProps.employee})
  }

  renderDescription() {
    if (this.state.show)
      return (
        <View style={{ flex: 1 }}>
          <Text>Merge</Text>
        </View>
      )
  }

  renderHour () {
    let hour=this.props.class.hour;
    let minutes='';

    if (this.props.class.minutes < 10) { 
      minutes = `0${this.props.class.minutes}`;
    } else {
      minutes = this.props.class.minutes;
    }

    return (
      <Text style={styles.titleStyle}>
        {hour}:{minutes}-{this.props.class.employeeUid}
      </Text>
    )
  }

  render() {
    LayoutAnimation.spring()
    console.log(this.state.employee);

    return (
      <TouchableWithoutFeedback 
        onPress={()=>{this.setState({show:!this.state.show})}}
      >
        <View>
          <CardSection>
            { console.log('rendered!!!!!') }
            { this.state.employee !==null ? <Text>123</Text> : null }
          </CardSection>
          { this.renderDescription() }
        </View>
      </TouchableWithoutFeedback>
    );
  }
} 

const styles = {
  titleStyle: {
    fontSize: 18,
    paddingLeft: 15,
  }
}

export default FlatListItem;

Способ передачи реквизитов в FLatListItem:

<ListView
                    enableEmptySections
                    dataSource={this.props.dataSource}
                    renderRow={(classi) => {
                        if (this.state.employees) {
                            const date = new Date();
                            const year = date.getFullYear();
                            const month = date.getMonth() + 1;
                            const day = date.getDate();
                            let wantedEmployee = null;
                            if (this.state.employees !== null) {
                                this.state.employees.forEach(employee => {
                                    if (employee.uid === classi.employeeUid)
                                        wantedEmployee = employee;
                                });
                                if (classi.year === year && classi.month === month && day === classi.day)
                                    return <FlatListItem class={classi} employee={wantedEmployee} />;
                                else
                                    return null;
                            }
                            else
                                return null;
                        }
                    }

                    }

this.state.employees устанавливается из выборки из firebase, поэтому я проверяю, что состояние равно нулю. В файле console.logs из FlatItemList, если я введу console.log («сделал это !!») вместо 123:

23:22:35: null
23:22:35: rendered!!!!!
23:22:35: Object {
23:22:35:   "cnp": "3",
23:22:35:   "name": "3",
23:22:35:   "phone": "3",
23:22:35:   "registru": "3",
23:22:35:   "serie": "3",
23:22:35:   "shift": "Luni",
23:22:35:   "uid": "-LLugVdZk3wJ1LbgDuEU",
23:22:35: }
23:22:35: rendered!!!!!
23:22:35: did it!! 

чтобы вы могли ясно видеть, что if (this.state.employees! == null) из

<ListView
                enableEmptySections
                dataSource={this.props.dataSource}
                renderRow={(classi) => {
                    if (this.state.employees) {
                        const date = new Date();
                        const year = date.getFullYear();
                        const month = date.getMonth() + 1;
                        const day = date.getDate();
                        let wantedEmployee = null;
                        if (this.state.employees !== null) {
                            this.state.employees.forEach(employee => {
                                if (employee.uid === classi.employeeUid)
                                    wantedEmployee = employee;
                            });
                            if (classi.year === year && classi.month === month && day === classi.day)
                                return <FlatListItem class={classi} employee={wantedEmployee} />;
                            else
                                return null;
                        }
                        else
                            return null;
                    }
                }

                }

вообще не работает. Есть идеи?

Ответы [ 2 ]

0 голосов
/ 08 сентября 2018

У вас есть веская причина, по которой вы используете componentWillReceiveProps?

Если нет, я думаю, что componentDidMount должен работать с этим делом.

componentDidMount() {
  // receive wantedEmployee from parent component set default value to be null if employee prop wasn't passed from parent component
  const {employee = null} = this.props;       

  // update employee state with employee from this.props
  this.setState({ employee }) // same as {employee: employee}
}

Кроме того, этот компонент будет повторно визуализировать свои дочерние элементы с обновленным состоянием, если состояние в ListView изменилось. Если есть какая-либо причина, по которой вы собираетесь использовать componentWillReceiveProps, пожалуйста, сообщите мне с комментарием.

0 голосов
/ 08 сентября 2018

Это потому, что функция рендеринга срабатывает перед componentWillReceiveProps, поэтому console.log имеет значение null, когда он получает вызов, так как состояние еще не обновлено.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...