我开始学习反应原生和构建Android app.so我面临一些设置和获取组件的属性的问题。我的代码
我有两个名为content-container和bar-chart的组件。在content-container里面,这是我的代码块:
state = {
barChartResponse: {},
arcChartResponse: {},
stackChartResponse: {},
lineChartResponse: {},
token:'abc',
};
componentWillMount() {
this.setState({token:'xyz'});
}
render() {
return (
<ScrollView>
<BarChart chartData = {this.state.token} />
</ScrollView>
);
}
现在我想在条形图组件中获取此属性,如下所示:
constructor(props) {
super(props);
Alert.alert("ChartData is : ",props.chartData);
}
它显示我默认情况下我在状态对象中设置的值,即abc,但我想要更新的值。请帮我看看我做错了什么.......提前谢谢。
您可以使用componentWillRecieveProps
,但不推荐使用,在RN> 54中,您可以使用componentDidUpdate
或getDerivedStateFromProps
从父级获取状态,如下所示:
componentDidUpdate(nextProps){
if (this.props.chartData !== nextProps.chartData) {
alert(nextProps.chartData)
}
}
要么
static getDerivedStateFromProps(props, current_state) {
if (current_state.chartData !== props.chartData) {
return {
chartData: props.chartData,
}
}
}
您需要更新它将自动反映在子组件中的父组件的状态,但下次您将在componentWillRecieveProps(nextProps)中接收然后渲染方法。
例如:
state = {
barChartResponse: {},
arcChartResponse: {},
stackChartResponse: {},
lineChartResponse: {},
token:'abc',
};
componentWillMount() {
this.setState({token:'xyz'});
}
updateState = () => {
this.setState({token: "newToken"})
}
render() {
return (
<ScrollView>
<Button onPress={this.updateState}>update State</Button>
<BarChart chartData = {this.state.token} />
</ScrollView>
);
}
在BarChart.js
componentWillRecieveProps(nextProps) {
// you can compare props here
if(this.props.chartData !== nextProps.chartData) {
alert(nextProps.chartData)
}
}