【问题标题】:Get the error of a JSON Validation List in ReactJS在 ReactJS 中获取 JSON 验证列表的错误
【发布时间】:2020-02-16 15:22:32
【问题描述】:

在我的 api 测试中,它能够如下图所示运行。但是,当我尝试在 React.JS 中编码时,无法传入用户 ID。这是什么问题?

但是当我尝试在前端编码时,无法将用户 ID 传递给 api。 考虑下面的代码:

  constructor (props){
    super(props);
    const Users_id = localStorage.getItem('id');
    this.state ={
      users_id: Users_id,
      event_name: '',
      event_email: '',
      event_description: '',
      event_type: '',
      event_location: '',
      start_date: '',
      end_date: '',
      history: PropTypes.object.isRequired
    }
    this.create = this.create.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  create(){
    // const loginEmail = localStorage.getItem('loginEmail');
    const Users_id = localStorage.getItem('id');
    this.setState({Users_id})
    // console.log(loginEmail)
    PostData('api/event/submit', this.state).then ((result) => {
        let responseJSON = result;
        console.log(responseJSON);
        console.log(this.state)

      });
   }

console.log(responseJSON) 中显示的错误:

//更新后的数据

    return new Promise((resolve, reject) => {
        fetch( BaseUrl+type, {
            method: "POST",
            body: JSON.stringify(userData),
            Accept: 'application/json',
            // mode: 'no-cors',
            headers: 
                { 
                    'Content-Type': 'application/json' 
                },
          })
        .then((response) => response.json())
        .then((responseJson) => {
            resolve(responseJson);
        })
        .catch((error)=>{
            console.error('Error:', error);
        })

    });

【问题讨论】:

  • 您的 API 是否期望 users_id 为数字?还是字符串化的数字?
  • @Jacob ya,users_id 是数字。
  • 我相信 getItem 返回一个字符串。尝试在更新状态之前输入console.log(typeof Users_id)
  • 你能展示你的 PostData 方法的代码吗?
  • @Jacob 没错,控制台日志的响应是字符串。那么有没有办法将字符串转换为数字呢?

标签: json reactjs api response


【解决方案1】:

Storage.getItem 返回一个字符串。 id 应该转换为数字

const Users_id = parseInt(localStorage.getItem('id'));

您可能需要在发送之前检查isNaN(Users_id)。或者让它失败,然后处理错误。

【讨论】:

    【解决方案2】:

    在插入 props 之前,你需要检查用户 id 是否存在于本地存储中

        super(props);
        const Users_id = localStorage.getItem('id') || '';
        this.state ={
          users_id: Users_id,
          event_name: '',
          event_email: '',
          event_description: '',
          event_type: '',
          event_location: '',
          start_date: '',
          end_date: '',
          history: PropTypes.object.isRequired
        }
    

    当你想设置状态时,你需要传递你在状态中使用的相同名称

    const Users_id = localStorage.getItem('id');
    if(Users_id){
    this.setState({users_id: Users_id})
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 1970-01-01
      • 2013-01-17
      • 2019-05-19
      • 2019-07-09
      • 2021-06-19
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      相关资源
      最近更新 更多