簡體   English   中英

有時未經授權,有時返回響應,在 React 中使用 fetch

[英]Sometimes unauthorized, sometimes return response, with fetch in React

我希望你能幫助我。

我正在做一個簡單的獲取,希望它在 DOM 被渲染之前被執行。

但是,有時它會因未授權而返回 401 答案,因為道具未定義,有時它會返回正確答案。

建議?

constructor(props) {
    super(props);
    this.state = { 
        renderizado: false,
        token: props.token,
    };
}

componentDidMount() {
        const test = this.state.token;
        if(test !== undefined){
            fetch("url",
                {
                    headers: {
                        "X-Requested-With": "XMLHttpRequest",
                        "Content-Type": "application/json",
                        Authorization: "Bearer " + test,
                    },
                }
            ) 
            .then(response => response.json())
            .then(data => this.setState({ data: data, renderizado: true }));
        }
        else
        {
            console.log("viene undefined");
        }
    }   

render() {
        return (
            <div>
                { this.state.renderizado ? <h1>Cargado</h1> : null }
            </div>
        );
    }

我已經在這兩天了,我是一個業余愛好者。

謝謝你。

試試這個:(基本上我所做的就是從componentDidMount更改為componentDidUpdate

constructor(props) {
  super(props);
  this.state = {
    renderizado: false,
    token: props.token,
    data: null,
  };
}

componentDidUpdate() {
  const { token } = this.state;
  if (token) {
    fetch('url', {
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + token,
      },
    })
      .then((response) => response.json())
      .then((data) => this.setState({ data, renderizado: true }));
  } else {
    console.log('viene undefined');
  }
}

render() {
  const { renderizado, data } = this.state;

  return (
    <div>
      {renderizado ? (
        <h1>
          <pre>{JSON.stringify(data, null, 4)}</pre>
        </h1>
      ) : null}
    </div>
  );
}

你試過if(test != undefined)嗎?

也許那是一個 Promise 尚未解決,並且該組件之前有時已安裝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM