首页 > 解决方案 > setState() 不会立即改变状态

问题描述

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

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>
  );
  }

导航.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>
);
}

标签: javascriptreactjscallbackfetch

解决方案


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

而是像下面这样使用:-

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

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>
);
}

推荐阅读