【发布时间】:2019-12-14 01:17:21
【问题描述】:
谁能解释一下为什么这不能像我预期的那样工作。我正在尝试使用反应导航从一个屏幕导航到另一个屏幕,并且我想将一个状态的值从一个屏幕传递到另一个屏幕(我将我的值从父组件中的状态以及我的 2 个更改状态值的函数中保存)。当我导航到我的子组件时,我从状态和两个函数中传递值。
主要问题是,当我触发 2 个功能时,我在子屏幕上看不到任何更改,但是当我返回父屏幕时,更改已经完成并且它们在屏幕上可见。
我尝试使用this.forceUpdate(),但仍然无法使用。
有什么帮助吗?
这是我的父组件,我在其中保存状态和更改状态的函数
import React from 'react';
import { Text, View, TouchableHighlight, Image, ScrollView, FlatList } from 'react-native';
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 2
};
}
incrementValue = () => {
this.setState(prevState => ({
value: prevState.value + 1
}));
};
decrementValue = () => {
this.setState(prevState => ({
value: prevState.value - 1
}));
};
onPressButton = () => {
this.props.navigation.navigate('Child', {
value: this.state.value,
incrementValue: this.incrementValue.bind(this),
decrementValue: this.decrementValue.bind(this)
});
};
render() {
return (
<View>
<Text>parent component</Text>
<TouchableHighlight onPress={() => this.onPressButton()}>
<Text style={{ color: 'red' }}>go to child</Text>
</TouchableHighlight>
<Text>state value : {this.state.value}</Text>
</View>
);
}
}
这是我的子组件:
import React from 'react';
import { Text, View, TouchableHighlight, Image, ScrollView, FlatList } from 'react-native';
export default class Child extends React.Component {
constructor(props) {
super(props);
}
onPressIncrement = () => {
this.props.navigation.state.params.incrementValue();
this.forceUpdate();
};
onPressDecrement = () => {
this.props.navigation.state.params.decrementValue();
this.forceUpdate();
};
render() {
const { navigation } = this.props;
const value = navigation.getParam('value');
alert(value);
return (
<View>
<Text>Child component</Text>
<Text>{value}</Text>
<TouchableHighlight onPress={() => this.onPressIncrement()}>
<Text>incrementValue</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.onPressDecrement()}>
<Text>decrementValue</Text>
</TouchableHighlight>
</View>
);
}
}
【问题讨论】:
标签: javascript react-native react-redux react-native-android react-native-navigation