问题
I am using React Navigation to route between screen. I have an initial screen which contains a FlatList
, onclick of an item I route to a new screen while passing params like this.
props.navigation.navigate('Details', {
id: props.id,
title: props.title
});
In the Details
screen I can receive it using the following code but how do I set the state considering it's a static function and I do not have access to this.setState()
.
static navigationOptions = ({navigation}) => {
const {params} = navigation.state;
console.log(params);
};
回答1:
This will allow you to handle it in the constructor, which is the other location anything that used to be placed in componentWillMount can go.
constructor(props) {
super(props)
this.state = {
params: props.navigation.state.params
}
}
For reference, by passing in the props as an argument to constructor and then running the super function on them, you gain the ability to set your initial state or run other one-time functions before any other life-cycle functions are called.
回答2:
Use componentWillMount, instead of navigationOptions
componentWillMount(){
this.setState({
params:this.props.navigation.state.params
})
}
回答3:
For anyone who is looking this is what I managed so far to get it working.
export default class Detail extends React.PureComponent {
state = {
id: this.props.navigation.getParam('id', -1),
title: this.props.navigation.getParam('title', null)
};
render() {
return (
. . .
);
}
}
This allows you to initialize the component with an initial state, might not be the best way and the code could definitely do with some destructuring but I'm not sure how to go about it so for now this works. Would love if someone could suggest a more efficient and performant way.
"dependencies": {
"react": "^16.3.1",
"react-native": "0.55.4",
"react-navigation": "^2.0.1"
}
来源:https://stackoverflow.com/questions/50372616/set-initial-state-from-navigation-props