我正在将我的应用程序从react-navigation 1.5升级到3.0.9。我不清楚组件状态管理有什么区别,但我确定有一些。这曾经工作得很好,现在它表现得很奇怪。看起来状态是以某种方式缓存的,浏览并回到这个组件,state.params.letter
仍然是相同的,即使我不需要它。如果我改变观点,不应该破坏国家吗?
该组件有一个非常简单的逻辑,它显示了FlatList
的项目。如果支持letter
存在,它只显示以该字母开头的项目。
export default class Search extends Component {
constructor(props) {
super(props);
}
DB = null;
componentDidMount(){
//check for the param "letter"
let L = this.props.navigation.state.params ? this.props.navigation.state.params.letter : null;
this.setState({
DB: L ? this.DB.getStartWith(L) : this.DB.getAll()
})
}
render() {
const { params } = this.props.navigation.state;
const { t, i18n, navigation } = this.props;
return (
<View>
<FlatList data={this.state.DB}
renderItem=({item}) => <Text> {item} </Text>
/>
</View>
);
}
}
反应导航堆栈导航器的工作方式,它存储不同屏幕的堆栈,以便当您使用后退按钮时,它会知道您上次访问的屏幕。当你传递一个像你的情况一样的参数时:
this.props.navigation.state.params.letter
状态存储在反应导航堆栈中并保持在那里直到您“破坏”屏幕(例如从该屏幕返回),例如,如果您的堆栈看起来像(screen1>搜索),然后您移动到screen2,以便它变为(screen1> search> screen2)搜索组件的内部状态将被破坏而不是反应导航状态,所以如果你回去参数字母将是相同的,破坏该参数的唯一方法是返回到screen1。另一种方法是使用redux之类的东西存储你的字母参数,一般来说我尽量避免使用react-navigation参数传递变量,除非它是与导航本身相关的参数(如导航选项)。