首页 文章

在fetch中反应本机使用导航道具

提问于
浏览
0

我很反应原生态 . 我在我的react-native应用程序中使用react navigation . 我将一些道具从一个屏幕传递到另一个屏幕,我需要使用其中一个道具来尝试在 componentDidMount 生命周期方法中执行 . 对于我尝试的所有内容,它会发送"type"键的值,但它不会为"location"键发送任何内容(请参阅下面的代码) . 有人可以帮助我解决我错过或做错的事吗?我已经尝试了几件事来通过道具,但还没有任何工作 .

componentDidMount() {
    const { params } = this.props.navigation.state;
    var data = {
      type: 'r',
      location: params.location
    }
    return fetch('http://myapisite', {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        }
      )
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        }, function() {
          // do something with new state
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

1 回答

  • 0

    我能够解决这个问题 . 我不是100%肯定为什么我没有工作,但当我把它改成以下时,它按预期工作:

    const {state} = this.props.navigation;
    var data = {
      type: 'restaurant',
      location: state.params.location
    }
    return fetch('http://mylink', {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        }
      )
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        }, function() {
          // do something with new state
        });
      })
      .catch((error) => {
        console.error(error);
      });
    

相关问题