首页 > 解决方案 > 在 react-native 中使用导航发送参数

问题描述

我正在学习使用导航,我在订单页面上有一个订单页面和一个 order_detail 页面,我创建了一个输入表单,并在将输入贡献到 order_detail 页面之前收集了输入

这是订单页面

 ongNavigationDetail = ()=>{
        let params = {
            origin: this.state.selectOrigin.id_origin,
            destinasi_sub_city : this.state.selectSubDestinasi.id_kecamatan
        }
        // console.log(params)
        this.props.navigation.navigate('orderdetail',{data:params})
    }

在 ongNavigationDetail 函数中,我将输入结果存储到一个变量中,即 params。控制台日志结果

{"destination_sub_city": "1", "origin": "39"}

在订单详情页面上,我想从订单页面获取输入结果并将其输入到 url

页面 order_detail

constructor(){
    super();
        this.state = {
            results: [],
    }
}

componentDidMount(){
    this.cekData();
}


cekData= () =>{
        let params = this.props.data; //the results of my order page input here
        const url = 'https://example/price?id_origin=${1}&id_destinasi=${39}'
        fetch(url)
        .then((response)=> response.json())
        .then((responseJson)=>{
        this.setState({
            results: responseJson.data.jenis,
            isLoading : false
        })
    }

问题是如何使用状态在订单页面上获取输入参数并输入 URL?这里 url 我使用手动值

谢谢 :)

标签: reactjsreact-nativenavigationstatenative

解决方案


根据您使用的 React Navigation 版本:

// Old versions
const { destination_sub_city } = this.props.navigation.state.params;
const destination_sub_city = this.props.navigation.getParam('destination_sub_city');

// Latest version (5.x)
const { destination_sub_city } = this.props.route.params;

对于 React Navigation v4.x,它会是这样的:

cekData = () => {
  const { 
    destinasi_sub_city,
    origin
  } = this.props.navigation.getParam('data');

  const url = `https://example/price?id_origin=${origin}&id_destinasi=${destinasi_sub_city}`;

  fetch(url)
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        results: responseJson.data.jenis,
        isLoading : false
      });
    });
};

推荐阅读