首页 > 解决方案 > 从渲染常量设置状态

问题描述

我想设置状态,就我而言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未定义之类的错误。有没有办法解决这个问题?感谢您的帮助!

标签: javascriptreactjsreact-native

解决方案


尝试使用 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)

推荐阅读