如何在本机反应中添加状态

时间:2021-06-14 09:44:16

标签: javascript json reactjs react-native state

我想添加两个状态,

状态的两个值都是使用 fetch 请求从 json 对象中提取的

 constructor(props) {
    super(props);
    this.state = {
     charge:0,
     total:0,
    };
  }

 dataFatch()
  {    
  const tot =  this.state.total;        
                fetch('https://xyz.in/app/reg.php', {
                method: 'POST',
                mode: 'no-cors',
                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                  'item_id':ids,
                  'func':'item_data',
                })
              }).then((response) => response.json())
              .then((json) => {

                  this.setState({'total':json.total});
                  this.setState({'charge':json.charge}); 

              }).catch((err) => { console.log(err); });
  }

但在获取数据后 charge=30total=80

我预制加法

Let add = this.state.charge+this.state.total;
console.log(add);

但结果是 3080 而不是 110

我该如何解决这个问题

1 个答案:

答案 0 :(得分:2)

看起来你在做连接字符串而不是数字

我没有在您的 api 请求函数中看到添加逻辑,但根据您的展示,您可以使用下面的方法修复它

let add = Number(this.state.charge) + Number(this.state.total);
console.log(add);

但重要的是你要明白你存储的状态不是数字而是字符串类型。

因此,在更新状态时,您可以确保它是数字而不是字符串,因此在执行 concat 时无需将其转换为数字。