javascript - 仅当过滤器设置为时,才在 url 中设置 'params filter'

标签 javascript reactjs axios

当我发送请求时,我从服务器收到错误 500。type20type30 未定义type30以后会补上值。如何设置'filter [status]': [type10, type20, type30],让type20type30只有在有的时候才会出现一个完成的值。

 this.setState({
  type10: 10,
  type20: '',
  type30: ''
})

handle = () => {
  {type10, type20, type30} = this.state;
  const params = {
    expand: 'project,labels',
    'filter[status]': [type10, type20, type30],
  }

  axios({
    url: `/api/v1/todos`,
    method: "GET",
    params
  })
  .then(res => { 
    console.log(res.data)
  })
  .catch(error => {
    console.log(error);
  }) 
}

最佳答案

你不能像那样访问状态,要么必须解构状态,要么直接从状态中使用它

 this.setState({
  type10: 10,
  type20: '',
  type30: ''
})

handle = () => {
  const params = {
    expand: 'project,labels',
    'filter[status]': [this.state.type10, this.state.type20, this.state.type30],
  }

  axios({
    url: `/api/v1/todos`,
    method: "GET",
    params
  })
  .then(res => { 
    console.log(res.data)
  })
  .catch(error => {
    console.log(error);
  }) 
}

 this.setState({
  type10: 10,
  type20: '',
  type30: ''
})

handle = () => {

  const {type10, type20, type30} = this.state 
  const params = {
    expand: 'project,labels',
    'filter[status]': [type10, type20, type30],
  }

  axios({
    url: `/api/v1/todos`,
    method: "GET",
    params
  })
  .then(res => { 
    console.log(res.data)
  })
  .catch(error => {
    console.log(error);
  }) 
}

你在评论中问到的事情意味着当你在你的状态下有一些属性时你会传递它但是当不在那里你不能设置如果你在你的对象中设置未定义的东西这将不会得到通过 Axios 对象。 在这里尝试这种方法,您将发送那些存储在状态中的数据。您不必担心要发送哪些数据,传播运营商会为您做这件事

this.setState({
  type10: 10,
  type20: '',
  type30: ''
})

handle = () => {


  const params = {
    expand: 'project,labels',
    'filter[status]': [...this.state],
  }

  axios({
    url: `/api/v1/todos`,
    method: "GET",
    params
  })
  .then(res => { 
    console.log(res.data)
  })
  .catch(error => {
    console.log(error);
  }) 
}

关于javascript - 仅当过滤器设置为时,才在 url 中设置 'params filter',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57658224/

相关文章:

javascript - Angular:将值传递回服务

javascript - 如何使用 Bing Maps AJAX Control v7 获取鼠标点击的纬度/经度

node.js - 如何将 'src' 设置为 webpack 中的资源根目录?

javascript - 无法使内联样式在 React 中工作

javascript - 如何使用具有嵌套属性的对象传播?

javascript - 如何使用 axios-retry 重试状态 200

javascript - 创建一个“加载更多”按钮,以增加从 API 获取的可见文章的数量

javascript - 使用 JS 以编程方式在 Safari 中打开一个新选项卡

javascript - 如何让一个图像指向一个按钮(我有多个版本,每个都指向一个特定的按钮)

javascript - text/plain 和 string 之间有区别吗?