【问题标题】:Can't assign response data to the state data and the response is not empty in React无法将响应数据分配给状态数据并且响应在 React 中不为空
【发布时间】:2021-03-16 02:35:39
【问题描述】:

我目前正在制作我的第一个 React API 应用程序,即使我将 res.data 分配给它不是空的,我也无法弄清楚什么状态数据是空的。 我也不知道如何在 div 中呈现所有这些内容。

这是 res.data 的 console.log 返回的内容:

(2) [{…}, {…}]
0: {user: {…}, available_amount: 4324324}
1: {user: {…}, available_amount: 43243243}
length: 2
__proto__: Array(0)

这是我的代码:

  class App extends Component{
        constructor(props) {
        super(props);
        let data
        this.state = {
          data: [],
          loaded: false,
          placeholder: "Loading"
        };
      }
    

    async componentDidMount(){
        let data;
        axios
            .get('http://127.0.0.1:8000/api/',{
                headers:{
                'Authorization': 'Token 8651a2b6c28ecd5cd25c0e67dfd7f3642a3d0029'
                }
            })
            .then(res => {
                this.setState(() => {
                    return {
                    data: res,
                    loaded: true
                };
                });
            })
            .then(console.log(this.state.data))

    }

【问题讨论】:

    标签: json reactjs api django-rest-framework


    【解决方案1】:

    试试下面... 将您的 setState 更改为 setState({...}) 和 记住loading

    import React, { Component } from "react";
    
    const arrayOne = [
      {
        id: 1,
        nome: "Ruan"
      },
      {
        id: 2,
        nome: "Paul Symon"
      },
      {
        id: 3,
        nome: "Renan Lucas"
      }
    ];
    
    export default class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          data: [],
          loading: true
        };
      }
    
      async componentDidMount() {
        setTimeout(() => {
          this.setState({ data: arrayOne, loading: false });
        }, 1000)
      }
    
      render() {
        return (
          <div>
            {this.state.loading ? (
              <h1>Carregando...</h1>
            ) : (
              <div>
                {this.state.data.map((i) => {
                  return <h1>{i.nome}</h1>;
                })}
              </div>
            )}
          </div>
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      setState 以异步方式工作,当您在then 中调用console.log 时,状态可能未更新。 setState 实际上接受回调作为其第二个参数,您可以在其中检查更新的状态:

      this.setState(() =&gt; {...}, () =&gt; { console.log(this.state.data) })

      顺便说一句,考虑到您的新状态不依赖于以前的状态,您可以只将对象传递给 setState 而不是函数:

      this.setState(
          {
              data: res,
              ...
          },
          () => {
              console.log(this.state.data)
          }
      )
      

      【讨论】:

        【解决方案3】:

        对之前的状态追加了新的状态而不是替换,代码可能是这样的。

        class App extends Component {
          constructor(props) {
            super(props);
            let data;
            this.state = {
              data: [],
              loaded: false,
              placeholder: "Loading",
            };
          }
        
          async componentDidMount() {
            let data;
            axios
              .get("http://127.0.0.1:8000/api/", {
                headers: {
                  Authorization: "Token 8651a2b6c28ecd5cd25c0e67dfd7f3642a3d0029",
                },
              })
              .then((res) => {
        -        this.setState(() => {
        -          return {
        -            data: res,
        -            loaded: true,
        -          };
        -        });
        +        this.setState((prev) => {
        +          return {
        +            data: prev.data.concat(res),
        +            loaded: true,
        +          };
        +        });
              })
              .then(console.log(this.state.data));
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2019-10-11
          • 2018-04-03
          • 1970-01-01
          • 2019-02-17
          • 2022-09-27
          • 1970-01-01
          • 2016-03-25
          • 2017-05-30
          • 2020-11-05
          相关资源
          最近更新 更多