如何调用回调函数? 还是在mapStateToProps获取数据后如何设置状态?
RegistrationContainers:
function mapStateToProps(state, props) {
return {
isRegistered: state.user.registered // isRegistered: 1
};
function mapDispatchToProps(dispatch, props) {
return {
registration:(data) => dispatch(registration(data))
};
RegistrationComponents:
onRegister(){
let email = this.state.email;
let password = this.state.password;
let registerData = {email:email,password:password};
registerData = JSON.stringify(registerData);
this.props.registration(registerData)
this.setState({isRegistered: this.props.isRegistered}) // isRegistered: undefined, but second run after is correct
注册操作:
export function OnRegistration(registered) {
/* ... */
return registered }
export function registration(regData) {
return (dispatch) => {
sendDataToApi(regData, "registration",(isRegistered)=>{
dispatch({
type: ON_REGISTRATION,
registered: isRegistered
})
})
}
}
注册减少器:
const initialState = {};
export function loginReducer(state = initialState, action) {
switch(action.type){
case REGISTRATION:
return Object.assign({},state,{
registered: action.registered
})
}
return state; }
容器获取当前状态,但是容器props无法从组件到达。
答案 0 :(得分:-1)
通过添加callback()函数来修改您的方法。即
function mapDispatchToProps(dispatch, props) {
return {
registration:(data, cb = null) => dispatch(registration(data, cb))
};
并将registration(data)
方法修改为:
registration(data, cb) {
/* your code here */
/* on successful registration, set user.registered to true in redux and
then call cb function */
cb && cb();
}
将onRegister()
方法修改为:
onRegister(){
let email = this.state.email;
let password = this.state.password;
let registerData = {email:email,password:password};
registerData = JSON.stringify(registerData);
this.props.registration(registerData, () => {
this.setState({isRegistered: this.props.isRegistered})
}
})