React-native构造函数和componentWillMount范围问题

时间:2018-02-24 22:58:08

标签: javascript reactjs react-native

我想用地图显示我的数组monthDays中的所有项目 问题是我需要在componetWillMount中执行一些逻辑,通过在循环中将项目推送到它来创建数组。
我在componetWillMount中所做的更改不会影响构造函数中的数组 对不起,如果我不清楚,我的英语不是那么好 这是代码:

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class Calendar extends Component {
  constructor(props){
    super(props);
    this.state = {text: ''};
    this.monthDays = ['I want to put this array'];
  }
  componentWillMount(){
    let monthDays = ['in this scope'];
    let defineDays = Number(this.props.days);
    let daysCount = 1;
    let x = 0;

    while (monthDays.length < defineDays) {
      monthDays.push(daysCount);
      daysCount++;
      this.setState({ text : monthDays[x]});
      x++;
    }
  }
  render() {
    return (
      <View style={styles.container}>
      {this.monthDays.map(( teste, key ) => (
        <View key = { key }>
          <Text>{ teste }</Text>
        </View>
      ))}
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

Ps:defineDays只收到一个具有月份天数的道具

2 个答案:

答案 0 :(得分:0)

试试这个:

export default class Calendar extends React.Component{

    constructor(){
       super();
       this.mapFunction = this.mapFunction.bind(this);
    }
    function mapFunction() {
       var arr = []
       for(var dayscount=0; dayscount < this.props.days; dayscount++){
           arr.push(dayscount);
       }
       return arr.map((test, key) => {
            return (
              <View key = { key }>
                <Text>{ test }</Text>
              </View>
            )
       })
    }

    render(){
       return(
          <View>
            { this.mapFunction }
          </View>
       )
    }
}

确保您正确设置this.props.days并且它的值是整数。

答案 1 :(得分:0)

你可以试试这个:

componentWillMount() {
  let monthDays = ['in this scope'];
  let defineDays = Number(this.props.days);
  let daysCount = 1;
  let x = 0;

  while (monthDays.length < defineDays) {
    monthDays.push(daysCount);
    daysCount++;
    this.setState({ text: monthDays[x] });
    x++;
  }

  // Assign the new values to your current array
  this.monthDays = monthDays;
}

如果您想要保持componentWillReceiveProps更新,那么如果您要在this.monthDays中执行同样的操作,那么您将获得道具新道具。