React Native:将props值赋给state

时间:2017-11-20 20:31:52

标签: reactjs react-native

有人可以告诉我如何将props中的值分配给状态值吗?

例如,下面的组件从父组件中获取几个值作为props。

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



export default class Logitem extends Component {

  constructor(props)  {
    super(props);
    const { logstringdate, bmi, weight, logdate } = this.props;
  }

  state = {
    selecteddate: '',
    selectedweight: ''

  }

onWeightClick = () => {
  this.setState({ selecteddate: this.props.logdate });
  console.log('Value in props==>'+this.props.logdate);
  console.log('The selecteddate in the state ==> '+ this.state.selecteddate);
}


render() {

  return (
    <View style={styles.containerStyle}>
              <View style={styles.headerContentStyle}>
                    <Text>{this.props.logstringdate}</Text>
                    <Text>{this.props.bmi}</Text>
              </View>
              <View style={styles.thumbnailContainerStyle}>
                    <Text onPress={this.onWeightClick}>{this.props.weight}</Text>
              </View>
    </View>
  );

}
};

const styles = {
  containerStyle: {
    borderWidth: 1,
    borderRadius: 2,
    borderColor: '#ddd',
    borderBottomWidth: 0,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
    marginLeft: 5,
    marginRight: 5,
    marginTop:10,
  },
  thumbnailContainerStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 10,
    marginRight: 10,
    flexDirection: 'row'

  },
  headerContentStyle: {
    flexDirection: 'column',
    justifyContent: 'space-around'
  },
};

传递给此LogItem组件的道具是logstringdate, bmi, weight, logdate

我在按下事件时设置状态(selecteddate)。

事件被触发但由于某种原因this.setState无效(即没有将状态值赋给道具)。

我已经确认道具确实通过了,而且它不是空的。

我的输出

enter image description here

1 个答案:

答案 0 :(得分:4)

那是因为setState是异步的。它并没有立即真正更新国家 setState有第二个参数,它是一个在设置状态后立即调用的回调。

  onWeightClick = () => {
    this.setState({ selecteddate: this.props.logdate }, () => {

      console.log('Value in props==>' + this.props.logdate);
      console.log('The selecteddate in the state ==> ' + this.state.selecteddate);
    });
  }