【问题标题】:How to add a state into a api fetch()如何将状态添加到 api fetch()
【发布时间】:2018-12-30 23:19:11
【问题描述】:

您好,我需要在我的 API 获取中添加一个状态,但很难理解为什么当状态为空字符串时它可以工作,但如果状态内有字符串则无法工作,请查看示例

这个想法是用户在输入中输入新文本,更新状态搜索,然后更新获取 url,以便他们可以搜索数据库

示例工作代码(注意状态搜索为空)

export default class ThirdScreen extends React.Component {
  state = {
    search: '',
    image: ''
  }


  componentDidMount() {
    this.fetchsa();
  }

  fetchsa = () => {
    const {search} = this.state;

    fetch(`https://xxx/search?q=moon&media_type=image`)
    .then((response) => response.json())
    .then((result) => this.setState({
      image: result.collection.items[0].links[0].href
    }))

  }

示例代码无效

export default class ThirdScreen extends React.Component {
  state = {
    search: 'moon', //Notice this is not empty and now causes an error
    image: ''
  }


  componentDidMount() {
    this.fetchsa();
  }

  fetchsa = () => {
    const {search} = this.state;

    fetch(`https://xxx/search?q='${search}'&media_type=image`)
    .then((response) => response.json())
    .then((result) => this.setState({
      image: result.collection.items[0].links[0].href
    }))

  }

【问题讨论】:

  • 你的错误在result.collection.items[0].links这种解构很容易出错。你确定 api 的响应有预期的结果吗?

标签: json reactjs api react-native


【解决方案1】:

问题在于您的fetch URL 中的单引号

const search = 'moon';
fetch(`https://xxx/search?q='${search}'&media_type=image`)

不一样
fetch(`https://xxx/search?q=moon&media_type=image`)

API 请求通过'moon' 而不是moon,但未找到结果。

不过没关系:

fetch(`https://xxx/search?q=${search}&media_type=image`)

所以:

  1. 去掉${search}周围的单引号。
  2. 未找到结果时处理空的items 数组。

例如:

fetch(`https://xxx/search?q=${search}&media_type=image`)
    .then((response) => response.json())
    .then((result) => result.collection.items.length > 0 && this.setState({
        image: result.collection.items[0].links[0].href
    }))

【讨论】:

    【解决方案2】:

    试试这个:

    export default class ThirdScreen extends React.Component {
      state = {
        search: 'moon', //Notice this is not empty and now causes an error
        image: ''
      }
    
    
     componentDidMount() {
       this.fetchsa();
     }
    
     fetchsa = () => {
     const {search} = this.state;
    
     fetch(`https://xxx/search?q='${search}'&media_type=image`)
    .then((response) => response.json())
    .then((result) => this.setState({
      result.collection && result.collection.items[0] && result.collection.items[0].links[0] ?image: result.collection.items[0].links[0].href:null
    }))
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 2021-12-18
      • 2019-11-03
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多