如何在 React Native 中发送参数

how to send param in react native

这里我进行了登录,登录成功后我将id参数发送到首页, 在主页上,我根据登录用户 ID 显示数据。我在登录页面发送了一个参数。

之后我获取到主页的参数,但是这里的结果是空的。 如何正确解析数据?

页面登录

 //function login 
    fetch (......)
      .then((response) => response.json())
            .then((responseJson) => {
              if(responseJson.status == 'ok'){
                this.props.navigation.navigate('home', { id_user: id_user });
              }
              else if(responseJson.status == 'failed') {
              ....
             }


    <Button block info style={styles.mainBtn} onPress={this.login}>
       <Text style={styles.btnText}>Submit</Text>
    </Button>

首页

componentDidMount(){
      const { params } = this.props.navigation.state; 
      console.log(params)

      const url = 'https://example.com/data?id_user='+params.id_user
      fetch(url)
      .then((response)=> response.json())
      .then((responseJson)=>{
        // console.log(responseJson.data)
          this.setState({
              dataSource: responseJson.data,
              isLoading : false
          })
      })
      .catch((error)=>{
          console.log(error)
      })
  }

在首页,这里我想解析正在记录的id数据,但是我console的时候结果是null

在您的 Home 屏幕中,尝试在 componentDidMount 生命周期方法中像这样获取 id_user

componentDidMount(){
      const id = this.props.navigation.state.params.id_user
      console.log(id)
      //...rest of the code
}

如果这不起作用,请像这样在 Login 屏幕中配置您的 navigation 语句。

if(responseJson.status == 'ok'){
  this.props.navigation.navigate({'home', { id_user: id_user }});
}