在我的表单中,我正在尝试添加我的' userExists'确定用户名是否已被采取的行动。我让asyncValidate成功地使用了redux-form的文档。现在我想添加我的动作但是我找不到任何好的例子来将它与Promise的需要联系起来。我可以在调度程序中添加我的操作但是我得到了一个错误,redux需要通过Promise发送。
有没有怎么做的例子?
FormComponent.jsx
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const asyncValidate = (values , dispatch) => {
/// ?... dispatch(userExists({ email : values.email }))
return sleep(1000).then(() => {
// simulate server latency
if (['john', 'paul', 'george', 'ringo'].includes(values.username)) {
throw {username: 'That username is taken'}
}
})
}
userAction.jsx
export function userExists(params) {
return (dispatch) => {
axios.get('http://apiserver.com/api/users.php', {
params : { ...params }
})
.then((response) => {
console.log(response.data);
dispatch({ type : "FETCH_USER_FULFILLED", payload : response.data })
})
.catch((err) => {
dispatch({ type : "FETCH_USER_REJECTED", payload : err })
});
}
}
userReducer.jsx
export default function reducer(state = {
user : {
id : null,
firstName : null,
lastName : null,
email : null,
meta : {
zipCode : null,
streetNumber : null,
city : null,
},
},
fetching : false,
fetched : false,
error : null
}, action) {
switch (action.type) {
case 'FETCH_USER_PENDING' : {
return {...state,
fetching : true
}
break;
}
case "FETCH_USER_REJECTED" : {
return {...state,
fetching : false, error : action.payload
}
break;
}
case "FETCH_USER_FULFILLED" : {
return {...state,
fetched : true, user : action.payload
}
break;
}
case "ADD_USER" : {
return {...state,
user : action.payload }
break;
}
}
return state;
}
store.jsx
import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import promise from 'redux-promise-middleware';
import reducers from './reducers/Reducers.jsx';
const middleware = applyMiddleware(promise(), thunk, createLogger());
export default createStore(reducers, middleware);
答案 0 :(得分:1)
以下是带有dispatch的动作asyncValidate的示例。我希望这会有所帮助。
export const asyncValidate = (values, dispatch) => {
return new Promise((resolve, reject) => {
dispatch({
type: types.GET_USERNAME_DATA,
promise: client => client.post('/api', values),
}).then((result) => {
if (result.data.code !== 200) reject({username: 'That username is taken'});
else resolve();
});
});
};