简体   繁体   English

setState()不立即改变状态

[英]setState() not mutating state immediately

I have a parent component that uses a get request to retrieve a JWT Token and then passes that token as a prop down to a child component. 我有一个父组件,该组件使用get请求检索JWT令牌,然后将该令牌作为prop传递给子组件。 That token gets passed in another get request to authorize and retrieve data. 该令牌在另一个get请求中传递,以授权和检索数据。 On the method that does that get request, I am using setState after the request is successful to update the state of an empty array. 在执行请求的方法上,请求成功更新后,我将使用setState更新空数组的状态。 The problem is that it is lagging behind due to setState not mutating the state quickly enough and the array is staying empty. 问题是由于setState不能足够快地使状态变化而使它滞后并且数组保持为空。 I am trying to pass that array value as a prop to a child component. 我正在尝试将该数组值作为对子组件的支持。 Any help is appreciated. 任何帮助表示赞赏。

App.js - Parent Component 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 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>
);
}

You should never rely on timeout, because you never know the network latency. 您永远不要依赖超时,因为您永远不知道网络延迟。

Rather use like below :- 而是使用如下:

export default class Navigation extends Component { 导出默认类导航扩展Component {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM