首页 > 解决方案 > 如何将来自先前活动的文本数据发送到 API

问题描述

我是反应原生的新手。我想将我的文本数据发送到 API。怎么做?

从这个编码中,我可以从 FirstActivity 获取数据,但是如何在第二个活动中将该数据发送到 API?

标签: javascriptreact-native

解决方案


你在接收数据this.props.navigation.state.params.no吗?

如果是这样,您可以在componentDidMount中发送它,当您导航到第二页时应该触发它,或者您可以使用一些react-navigation 生命周期。例如,我将使用 componentDidMount

 class SecondActivity extends Component{
         static navigationOptions =
            {
                title: "Second Activity"
            };
    componentDidMount(){  //this will trigger everytime the screen is mounted
       this.callAPI() /we call a function that handles the API call 
    }
    async callAPI(){ //is async because i like it 7u7
      var numberReceived = this.props.navigation.state.params.no
       var Result = await fetch ....... //call API here and use the number received variable in it
    }
    render() {
            return (
            <View style= {styles.MainContainer}>
                <Text style={styles.textStyle}>
                1 = {this.props.navigation.state.params.no}
                </Text>
            </View>
            )}
    }

实现实际上取决于您尝试使用的 API。他们应该有一些文档来解释你应该做什么来调用 API。当然,你应该对fetch API 或者 xmlhttprequest API有一些基本的了解


推荐阅读