在我的情况下,我想设置状态feedbackLogId
,它需要调用一个函数,该函数将根据feedbackLogId
获取反馈的详细信息。但是,const是从上一个屏幕中获得的,我只能在render()方法中设置const。
这里,我从WebAPI提取数据并将其呈现在FlatList中,那里会有多个反馈。
dataSource = [{
"feedbackLogId": 1,
"name": "Test1",
"comment": "Hello",
}, {
"feedbackLogId": 2,
"name": "Test2",
"type": "Hi",
}, {
"feedbackLogId": 3,
"name": "Test3",
"type": "Morning",
}]
当我按下“反馈”之一时,我想导航到第二个屏幕,但是保存feedackLogId的值,以便我可以获取有关反馈的更多详细信息。
<TouchableOpacity style={styles.listItem}
onPress={() => this.props.navigation.navigate('FeedbackDetails', {value: item.feedbackLogId})}
>
</TouchableOpacity>
我已经尝试了许多方法,但是可能是props.navigation
未定义,或者是其他一些错误。
这是在构造函数(props)中完成的
constructor(props) {
super(props);
this.state = {
isLoaded: false,
dataSource: [],
feedbackLogId: ''
}
this.getPendingDetails = getPendingDetails.bind(this)
}
我想在componentDidMount()中调用函数getPendingDetails,这是我需要我的feedbackLogId的地方。
componentDidMount() {
//this is where I would need the state of feedbackLogId
this.getPendingDetails(this.state.feedbackLogId);
}
只有在渲染器中,我才能获得从另一个屏幕传递的数据的值
const feedbackLogId = this.props.navigation.getParam('value', 'nothing')
我曾尝试在屏幕的其他部分调用const feedbackLogId = this.props.navigation.getParam('value', 'nothing')
,但遇到诸如this.props
不确定的错误。有办法解决这个问题吗?谢谢您的帮助!
尝试使用getDerivedStateFromProps
static getDerivedStateFromProps = (props, state) => {
console.log('props',props.navigation)
const feedbackLogId = props.navigation.getParam('value', 'nothing');
if(feedbackLogId){
this.getPendingDetails(feedbackLogId);
}
}
在您的构造函数中
this.getPendingDetails = getPendingDetails.bind(this)
到
this.getPendingDetails = this.getPendingDetails.bind(this)