【问题标题】:Axios get parsing boolean value to StringAxios 将布尔值解析为字符串
【发布时间】:2020-08-05 14:14:28
【问题描述】:

我正在尝试使用 Axios get 从 JSON 中获取所有内容,除了布尔值之外的所有内容,都没有解析为字符串(我正在添加当前 state.toString() 但不工作。或者有其他方式来显示它吗?在后端 api "isInstructed":true,

        const { id } = this.props.match.params
        axios.get(`/visitors/${id}`)
            .then(res => {
                this.setState({ visitors: res.data });   
        }

渲染

        
        return (
                 <h4>Is instructed? </h4>{this.state.visitors.isInstructed.toString()}        

【问题讨论】:

  • 怎么不工作了?
  • 您确定this.state.visitors.isInstructed 是您所期望的吗?你能控制台日志typeof this.state.visitors.isInstructed 并粘贴到这里吗?
  • 可以在 axios 调用前后为this.state.visitors 加值吗?
  • 什么不起作用?你有错误吗?
  • Console.log = 无法读取未定义的属性“访客”。但是作为回报,我有其他键,例如名称等,但不是布尔值 (i.e.this.state.visitors.name) 。那些不给出这个错误

标签: javascript reactjs axios


【解决方案1】:

this.state.visitors 的初始值可能是undefinednull

试试

return (
  <h4>Is instructed? </h4>
  {
   this.state.visitors && typeof this.state.visitors.isInstructed !== undefined ?
   this.state.visitors.isInstructed.toString() : 
   null
  }

【讨论】:

  • 是的!它有效,只需 {this.state.visitors.isInstructed && etc..} 就完美了!非常感谢!
【解决方案2】:

在 then 回调的调用中,就在正文中,尝试 console.log 你的 res 以查看你可以检索到什么或者它是否有一些调用错误

【讨论】:

    猜你喜欢
    • 2011-06-14
    • 2019-02-10
    • 2013-08-22
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多