【发布时间】:2019-09-23 14:42:34
【问题描述】:
在我的 React Native 应用程序中,我试图更改状态并触发组件的重新渲染。当NavBottom 调用this.props.navigation.navigate('captureView') 导航到CaptureView 时应该完成。状态更新应将CaptureView 照片状态变量重置为其原始值。
如何在 React Native 中使用 react-navigation on navigate 更改状态? 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)文档不同的方法:
-
https://reactjs.org/docs/react-component.html#componentdidmount -
componentDidMount()似乎是文档中推荐的方式,但在我的应用程序中它只被调用一次? - 即使
componentDidMount()在开始时被调用一次,但即便如此this.setState()是未定义的。奇怪,文档说它应该可用
【问题讨论】:
标签: ios react-native react-native-navigation react-state-management react-state