Javascript React组件中的异步操作
我正在使用React、Redux和Redux Thunk开发一个项目中的登录表单。使用Redux Thunk,我能够调度异步操作,比如将提交的登录表单传递到后端,并通过还原器将验证过的数据返回到状态。一旦组件获得所需的数据,它就可以毫无问题地重定向到所需的页面 问题是,在重定向用户之前,我需要将一些来自异步网络请求的数据写入本地存储。如果我不异步执行此操作,则会使用写入本地存储的初始状态值重定向用户 作为解决方案,我在React组件中使用承诺和超时来等待传入的数据 这种方法似乎有效,但感觉不对,有人能建议我更好的做法吗 这是组件中的代码,我过滤了大部分不相关的内容,使其尽可能简短Javascript React组件中的异步操作,javascript,reactjs,asynchronous,redux,redux-thunk,Javascript,Reactjs,Asynchronous,Redux,Redux Thunk,我正在使用React、Redux和Redux Thunk开发一个项目中的登录表单。使用Redux Thunk,我能够调度异步操作,比如将提交的登录表单传递到后端,并通过还原器将验证过的数据返回到状态。一旦组件获得所需的数据,它就可以毫无问题地重定向到所需的页面 问题是,在重定向用户之前,我需要将一些来自异步网络请求的数据写入本地存储。如果我不异步执行此操作,则会使用写入本地存储的初始状态值重定向用户 作为解决方案,我在React组件中使用承诺和超时来等待传入的数据 这种方法似乎有效,但感觉不对,
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {browserHistory} from 'react-router';
import {reduxForm} from 'redux-form';
import {connect} from 'react-redux';
import {validate} from './../utils/login/surfaceValidation';
import {inputAlerts} from './../utils/login/inputAlerts';
import {submitLogin} from './../redux/actions/index';
class Form extends Component {
componentWillReceiveProps(nextProps) {
if(nextProps.loginApproved) {
this.handleValidLogin();
}
}
handleLogin(props) {
this.props.submitLogin(props);
// submitLogin is async action handled by redux-thunk it returns
// this.props.loginApproved and if it's true componentWillReceiveProps
// will trigger.
}
handleValidLogin() {
this.writeToStorage()
.then(() => {
browserHistory.push('/main');
}).catch((err) => {
console.log(err);
});
}
writeToStorage(){
return new Promise((resolve, reject) => {
setTimeout(() =>{
localStorage.setItem('user',
JSON.stringify({
authenticated: true,
username: this.props.username,
id: this.props.id,
token: this.props.token
}));
}, 3000);
setTimeout(() => {
if(this.props.token != null) {
resolve();
console.log('got a token - resolving.');
} else {
reject();
console.log('no token - rejecting. ');
}
}, 4000);
});
}
render() {
return (
// Login form component is here.
// When user submits form, this.handleLogin() is called.
);
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({submitLogin});
}
function mapStateToProps(state) {
return {
loginApproved: state.login.loginApproved,
username: state.login.username,
id: state.login.id,
token: state.login.token
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Form);
据我所知,
localStorage.seItem
是同步的,因此您可以在重定向之前调用函数将数据保存到存储。问题是,将要写入的值在初始状态下定义为null。如果我不使用承诺,甚至不使用超时,那么初始状态值会在重定向之前写入。(将此添加到问题中。)听起来您在过早地调用handleValidLogin
。在你需要的道具到达之前,不要打电话给handleValidLogin。e、 g.if(nextrops.token&&nextrops.username&&nextrops.id){this.handleValidLogin();}
。我用nextrops调用handleValidLogin,而不是使用this.props参数,问题就消失了。我只是不明白,与我用react redux映射的道具相比,nextProps是如何提前的。componentWillReceiveProps
lifecycle钩子在道具更新后但在调用另一个渲染之前被调用。这意味着这不是提前,而是在组件使用新道具呈现之前-此时您的组件已经有了新道具,但要调用呈现