javascript - 从渲染常量设置状态
问题描述
我想设置状态,就我而言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
是未定义的,要么是其他几个错误。
这是在构造函数(道具)中完成的
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)
推荐阅读
- angular - Angular Http 与 HttpClient
- ruby-on-rails - 如何在 ruby on rails 中执行 .sh 文件
- php - 如何为目录中的所有 PHP 导入设置 ROOT?
- junit5 - 在 Eclipse 中使用 Maven SureFire 插件进行调试
- nativescript - NativeScript JavaScript 模式对话框在 iOS 上因 ViewHierarchy 错误而失败
- django - Django 我应该在单独的 django-app 中管理用户吗?
- sql - 使用多个部分词进行全文搜索
- java - 如何修复删除节点并在之后转到最后一个节点?
- dart - 使用vccode在flutter上异常Firebase Auth
- excel - 如何将多个文本文件(具有多行数据)读入二维数组?