如何获取嵌套在window.fetch中的setTimeout中组件的“ this”值?

时间:2019-08-26 15:37:59

标签: javascript fetch this settimeout react-component

所以我只把这个setTimeout嵌套在我的 window.fetch调用嵌套在我的FormComponent中。

这是window.fetch通话的一部分。

.then(function (response) {
    console.log(`response ${response}`)
      const { token } =  response.json();

    const loginOptions = {
      token,
      cookieOptions: { expires: 1 },
      callback: () => Router.push("/login")
    };

    setTimeout(
     function () {
      this.setState({ username: '', password: '' }.bind(this));
      login(loginOptions)
     }
      .bind(this),
     5000
    );

    return response.json();
   })

这是组件中更多的代码:

class RegisterForm extends Component {
 constructor(props) {
  super(props)

  this.state = {
   fadeUp: 'fade up',
   duration: 500,
   username: '',
   password: '',
   usernameError: false,
   passwordError: false,
   formSuccess: false,
   formError: false,
   userNameDup: false,
   isLoading: true
  }

  this.handleChange = this.handleChange.bind(this)
  this.handleBlur = this.handleBlur.bind(this)
  this.handleSubmit = this.handleSubmit.bind(this)
  this.handleErrors = this.handleErrors.bind(this)

 }

 componentDidMount() {
  this.setState({ isLoading: false })
 }

 handleSubmit(event) {
  event.preventDefault();

  window.fetch('http://localhost:8016/users/registration', {
   method: 'POST',
   headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
   body: JSON.stringify({ username_email: username, password: password })
  })
   .then(this.handleErrors)
   .then(function (response) {
    console.log(`response ${response}`)
      const { token } =  response.json();

  const loginOptions = {
   token,
   cookieOptions: { expires: 1 },
   callback: () => Router.push("/login")
  };

    setTimeout(
     function () {
      this.setState({ username: '', password: '' }.bind(this));
      login(loginOptions)
     }
      .bind(this),
     5000
    );

    return response.json()
   }).then(function (data) {
    console.log('User created:', data)
   }).catch(function (error) {
    console.log(error);
   });
 }

 render() {
  ...render jsx
}
export default RegisterForm

这是错误:

enter image description here

所以我只需要获取this值即可指向我的组件

0 个答案:

没有答案