setState()不立即改变状态

问题描述 投票:0回答:1

我有一个父组件,它使用get请求来检索JWT令牌,然后将该令牌作为prop传递给子组件。该令牌在另一个get请求中传递,以授权和检索数据。在获取请求的方法上,我在请求成功后使用setState来更新空数组的状态。问题是由于setState没有足够快地改变状态并且数组保持空白,因此它落后了。我试图将该数组值作为prop组件传递给子组件。任何帮助表示赞赏。

App.js - 父组件

class App extends Component {
 constructor(props) {
    super(props);

    this.state = {
      token: '',
    };

    this.getToken = this.getToken.bind(this);
  }

  getToken() {
    fetch('https://login-cmhmanagement.itg.cct-pubweb.com/nofapsaml', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
      },
    })
      .then(response => response.json())
      .then(data => {
        this.setState({ token: data });
      });
  }

  componentDidMount() {
    this.getToken();
  }

  render() {
  const { token } = this.state;
  return (
    <div className="app-container">
      <Navigation
        token={token}
      />
    </div>
  );
  }

Navigation.Js

export default class Navigation extends Component {



constructor(props) {
    super(props);

    this.state = {
      user: [],
      value: '',
    };
    this.getUserData = this.getUserData.bind(this);
  }

  componentDidMount() {
    setTimeout(() => {
      this.getUserData();
    }, 2000);
  }

  getUserData() {
    const { token } = this.props;
    let auth = token;
    fetch(url, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${auth}`,
      },
    })
      .then(response => response.json())
      .then(result => {
        this.setState({ user: result });
      });
  }
render() {
const { user } = this.state;
return (
  <SideBarStyled>
      <UserInfo
        authorizedLots={user.authorizeLots}
      />
  </SideBarStyled>
);
}
javascript reactjs callback fetch
1个回答
1
投票

您永远不应该依赖超时,因为您永远不会知道网络延迟。

而是使用如下: -

导出默认类导航扩展组件{

constructor(props) {
    super(props);

    this.state = {
      user: [],
      value: '',
    };
    this.getUserData = this.getUserData.bind(this);
  }

  componentDidUpdate(prevProps) {
    if(prevProps.token !== this.props.token){
      this.getUserData();
    }
  }

  getUserData() {
    const { token } = this.props;
    let auth = token;
    fetch(url, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${auth}`,
      },
    })
      .then(response => response.json())
      .then(result => {
        this.setState({ user: result });
      });
  }
render() {
const { user } = this.state;
return (
  <SideBarStyled>
      <UserInfo
        authorizedLots={user.authorizeLots}
      />
  </SideBarStyled>
);
}
© www.soinside.com 2019 - 2024. All rights reserved.