从渲染常量设置状态 [英] setting State from render const
问题描述
我想设置状态,在我的情况下,feedbackLogId
,它需要调用一个函数,该函数将根据 feedbackLogId
获取反馈的详细信息.但是,const 是从上一个屏幕中获取的,我只能在 render() 方法中设置 const.
I would like to setState, in my case, feedbackLogId
, which is required to called a function that will GET the details of feedback according to the feedbackLogId
. The const, however is gotten from the previous screen and I am only able to set the const in render() method.
在这里,我从 WebAPI 获取数据并将其呈现在会有多个反馈的 FlatList 中.
Here, I fetch the data from a WebAPI and render it in a FlatList where there will be multiple feedbacks.
dataSource = [{
"feedbackLogId": 1,
"name": "Test1",
"comment": "Hello",
}, {
"feedbackLogId": 2,
"name": "Test2",
"type": "Hi",
}, {
"feedbackLogId": 3,
"name": "Test3",
"type": "Morning",
}]
当我按下其中一个反馈时,我想导航到第二个屏幕,但保存 feedackLogId 的值,以便我可以获得有关反馈的更多详细信息.
When I press on one of the Feedback, I would like to get navigated to the second screen, but save the value of feedackLogId, so that i can get more details about the feedback.
<TouchableOpacity style={styles.listItem}
onPress={() => this.props.navigation.navigate('FeedbackDetails', {value: item.feedbackLogId})}
>
</TouchableOpacity>
第二屏
我尝试了很多方法,但要么是 props.navigation
未定义,要么是其他几个错误.
Second Screen
I have tried many methods, but it's either props.navigation
being undefined or several other errors.
这是在构造函数(props)中完成的
This is done in constructor(props)
constructor(props) {
super(props);
this.state = {
isLoaded: false,
dataSource: [],
feedbackLogId: ''
}
this.getPendingDetails = getPendingDetails.bind(this)
}
我想在 componentDidMount() 中调用 getPendingDetails 函数,这就是我需要反馈日志 ID 的地方.
I would like to call the function getPendingDetails in componentDidMount() and this is where I need my feedbackLogId.
componentDidMount() {
//this is where I would need the state of feedbackLogId
this.getPendingDetails(this.state.feedbackLogId);
}
只有在渲染内部,我才能获得从另一个屏幕传递过来的数据的值
Only inside render am I able get the value of the data passed from another screen
const feedbackLogId = this.props.navigation.getParam('value', 'nothing')
我尝试在屏幕的其他部分调用 const feedbackLogId = this.props.navigation.getParam('value', 'nothing')
但我收到了诸如 this 之类的错误.props
未定义.有没有办法解决这个问题?感谢您的帮助!
I have tried to call const feedbackLogId = this.props.navigation.getParam('value', 'nothing')
in other parts of the screen but am getting errors such as this.props
being undefined. Is there a way to solve this problem? Thank you for the help!
推荐答案
尝试使用 getDerivedStateFromProps
Try to use 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)
这篇关于从渲染常量设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!