【问题标题】:Correct way to pass parameters to fetch url in React Native?在 React Native 中传递参数以获取 url 的正确方法?
【发布时间】:2018-02-06 23:36:15
【问题描述】:
    componentDidMount() {
  var value =  AsyncStorage.getItem('name');
value.then((e)=>{
  this.setState({
   name: e.name
  })
})
const namme = encodeURIComponent(this.state.name);
      return fetch('http://www.example.com/user-list.php?name=${name}' , {
       method: 'POST',
       headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json',
       }

我还在学习 React Native,我想知道这是否是在 URL 中传递参数的正确方法?我也听说过使用 Redux 来帮助解决这个问题,但我不知道如何准确地实现它。

【问题讨论】:

  • 我将创建一个关于如何在 redux 中实现这一点的单独问题。

标签: react-native react-redux


【解决方案1】:

这是不正确的。 AsyncStorage 是一个与 react native 捆绑的 API,它允许您将数据存储在用户的设备上。您可以在 Facebook 的 documentation 上阅读更多相关信息。

你有点接近了,如果你想异步获取数据,React 组件的文档lifecycle events 说使用componentDidMount()

这是我如何使用

获取远程数据
componentDidMount() {
  const fetchConfig = {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  };
  fetch(`http://www.example.com/user-list.php?name=${name}`, fetchConfig)
    .then(res => res.json())
    .then(e => {
      this.setState({ name: e.name });
    });
}

这里需要注意几点:url 字符串使用的是反引号,而不是单引号。它被称为template literal

此外, fetch 正在返回一个承诺。 Fetch 让您了解您的请求返回的数据类型。为了将 JSON 解析为 JavaScript 对象,您调用 res.json(),它将向下一个 then 块返回一个承诺。一旦该承诺解决,您就可以根据返回的对象设置您的状态。

【讨论】:

  • 谢谢,但我收到一个错误:找不到变量名@Unicorn Master
  • 你能详细说明错误吗?它会告诉你它找不到哪个变量名吗?
【解决方案2】:

您是否尝试过 +this.state.name。

fetch('http://www.example.com/user-list.php?name='+this.state.text)
  //get status and append with data and return as one object
  .then(response =>  response.json())
  .then(responseobj => {
    this.setState({

     status:responseobj.msg,
   });

【讨论】:

    猜你喜欢
    • 2020-12-22
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2020-11-10
    • 2022-12-03
    • 2019-07-17
    • 2012-07-14
    • 1970-01-01
    相关资源
    最近更新 更多