【问题标题】:Undefined data after responseJson is entered into state [] in ReactJSReactJS中responseJson进入状态[]后未定义数据
【发布时间】:2020-11-26 09:40:51
【问题描述】:

我在这里遇到一个问题,即当我执行 Post API 并添加 console.log (responseJson) 时,数据会出现并且其内容是 (app_uid 和 app_number)。但是当我将API数据输入到dataApp[]状态并尝试console.log(this.state.dataApp)时,没有数据出现。

这是来自其 post API 函数的一段脚本:

 onTask = (pro, tas) => {
        fetch('https://bpm.***********.or.id/api/1.0/**********/cases/', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept-Encoding': 'gzip, deflate',
            'Authorization': 'Bearer ' + this.state.token,
          },
          body: JSON.stringify({
            'pro_uid': pro,
            'tas_uid': tas,
          }),
        })
        .then((response) => response.json())
        .then((responseJson) => {
          console.log(responseJson); //here the data appears
          this.setState({
            dataApp: responseJson,
          });
          console.log(this.state.dataApp); //but here does not appear any data
        });
      

希望我能在这里找到解决方案,非常感谢。

【问题讨论】:

    标签: json reactjs react-native api rest


    【解决方案1】:

    this.setState 是一个异步函数。

    含义 - 在您的示例中,您不会在控制台记录它的下一行看到它的结果,因为它还没有完成。

    尝试以下方法:

    this.setState({
      dataApp: responseJson,
    }, () => console.log(this.state.dataApp)); // console.log inside a callback
    

    要了解为什么它在回调中起作用,而不是在下一行中起作用,请查看MDN ArticleReact Documentation

    【讨论】:

    • 我试过这个之后,仍然没有显示任何数据,即使我只尝试了console.log(“数据会出现在这里”)
    【解决方案2】:

    setState() 是 React 中的 async 调用。因此,您不太可能在下一行中获得更新的状态值。您需要使用回调处理程序来获取更新后的值。

     onTask = (pro, tas) => {
    
            //Code you need to add
             var that = this;
             
            fetch('https://bpm.***********.or.id/api/1.0/**********/cases/', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Accept-Encoding': 'gzip, deflate',
                'Authorization': 'Bearer ' + this.state.token,
              },
              body: JSON.stringify({
                'pro_uid': pro,
                'tas_uid': tas,
              }),
            })
            .then((response) => response.json())
            .then((responseJson) => {
              console.log(responseJson); //here the data appears
             that.setState({
                dataApp: responseJson,
              }, () => {
        console.log("dataApp: ", that.state.dataApp);
       });
      });
    

    【讨论】:

    • 我试过这个之后,仍然没有显示任何数据,即使我只尝试了console.log(“数据会出现在这里”)
    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 2016-04-04
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多