在我的React Native应用程序中,我试图更改状态并触发组件的重新渲染。应该在NavBottom
调用this.props.navigation.navigate('captureView')
导航到CaptureView
时完成。状态更新应将CaptureView
照片状态变量重设为其原始值。
如何通过react-navigation
上的navigate
在React Native中更改状态? https://reactnavigation.org/docs/en/navigation-actions.html
CaptureView
是CaptureStack
import { createStackNavigator } from "react-navigation";
const CaptureStack = createStackNavigator({
captureView: CaptureView,
detailView: DetailView,
reportView: ReportView,
});
const Tab = createBottomTabNavigator({
capture: CaptureStack,
}, {
initialRouteName: 'capture',
tabBarComponent: NavBottom
});
CaptureView.js
:
import { StackActions, NavigationActions, NavigationEvents } from 'react-navigation';
class CaptureView extends Component {
static navigationOptions = {}
constructor(props) {
super(props);
console.log("CaptureView: constructor(props)");
}
componentDidMount() { // called just once
console.log("CaptureView: componentDidMount()");
// this.setState = { // undefined???
// photo: null // this needs to be RESET
// };
}
componentWillUnmount() {
console.log("CaptureView: componentWillUnmount()");
}
async onButtonPress() {
CameraService.takePicture().then((photo)=>{
this.setState({
photo: photo
});
// More actions
this.props.navigation.navigate(
"detailView",
{
id: 'DetailView',
photo
}
);
});
}
render() {
return (
<Camera
cameraSetter={(cam) => {
CameraService.setCamera(cam)
}}
photo={this.state.photo}
/>
<TouchableOpacity onPress={this.onButtonPress.bind(this)}>
<Text>TAKE PHOTO</Text>
</TouchableOpacity>
);
}
}
然后在应用程序的其他部分,有一个按钮可导航回到CaptureView。
NavBottom.js
:
export default class NavBottom extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View>
<TouchableOpacity onPress={() => this.props.navigation.navigate('captureView')}>
<Text>CAMERA</Text>
</TouchableOpacity>
</View >);
}
}
注释
我尝试了与失败的ReactJS(不是React Native)文档不同的方法:
componentDidMount()
似乎是文档中推荐的方式,但是在我的应用程序中,它仅被称为一次吗?componentDidMount()
,但即使this.setState()
仍未定义。很奇怪,文档说它应该可用答案 0 :(得分:2)
您是否尝试过使用导航事件来重置CaptureView组件的状态?
我认为onWillFocus
可以解决问题。
答案 1 :(得分:0)
React Navigation不会重新呈现位于Tab Naviagtor中的堆栈中的组件 为了执行强制的重新渲染,您可以像这样使用事件监听器
componentDidMount() {
this._navListener = this.props.navigation.addListener('didFocus', () => {
//perform any action you want, place your logic here
});
}
您还可以使用React Navigation的HOC withNavigation ,将( isFocused )道具传递给连接的组件
componentDidUpdate(prevProps, prevState) {
if(prevProps.isFocused !== this.props.isFocused){
//place your desired logic here
}
}
import { withNavigationFocus } from 'react-navigation';
...
...
...
export default withNavigationFocus(YourComponent)