我的 React Native 应用程序有一个非常简单的问题,我只想在每次单击按钮时执行一个函数,当有单独的类和组件时,它会变得复杂。
我有2个屏幕Dashboard
和Search
和2个部件Navbar
和Results
在 Dashboard 中,我获取一些用户输入并将其存储在selectedIngredients
变量中,并使用Navbar
组件执行位于同一文件中的函数。
<Navbar handle={() => this.switcher()} />
这个函数应该是魔法发生的地方(或者可能在 Search.js 屏幕中?)
switcher() {
const { navigate } = this.props.navigation;
navigate('Select', {passedData:this.state.selectedIngredients });
Alert.alert("send data to Search.js")
}
选择是Search.js
屏幕
一切正常,我使用预期的用户输入移动到预期的屏幕selectedIngredients
,这是Search.js
屏幕的第一个渲染。
componentDidMount() {
this.apiCall();
Alert.alert("did mount search.js")
}
之后我被卡住了,因为每次我点击我的 btnNavbar
并执行 switcher() 函数时,componentDidMount 不再运行,所以我必须通过点击另一个按钮刷新页面,这正是我想要的避免因为它对用户体验不利,就像真的很糟糕。我不想Results
自动更新组件,而只是用一个功能更新它。
下面的代码不是那么重要,它只显示apiCall
了Results
组件的功能和渲染,我不知道是否应该添加更多信息。请有人帮忙
apiCall() {
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.results,
});
})
}
componentDidMount() {
this.apiCall();
Alert.alert("did mount search.js")
}
render() {
return (
<View>
<Navbar title="Results" />
<Results results={this.state.data} />
</View>
);
}
}
我的尝试是添加this.props.apiCall()
切换器功能,但遇到了未定义的错误,比如 hey react native!请将此数据发送到Search.js
屏幕,当您到达时请执行apiCall
功能,它位于那里,而不是这里。