在mapDispatchToProps
中调用componentDidMount
函数时怎么样,
mapStateToProps
totalDoctorCount: state.doctors.totalDoctorCount
不会总是按时加载,我会undefined
得到console.log("this.props.totalDoctorCount: "+this.props.totalDoctorCount );
。
我知道这是async
的本质,但有没有办法解决它我在这里做错了什么。
完整代码:
doctorActions
export function getDoctors(filterType){
return function(dispatch){
axios.get("/api/doctors/"+filterType)
.then(function(response){
dispatch({type:"GET_DOCTORS",payload:response.data});
})
.catch(function(err){
dispatch({type:"GET_DOCTORS_REJECTED",payload:err});
})
}
}
export function getTotalDoctors(){
return function(dispatch){
axios.get("/api/getTotalDoctors/")
.then(function(response){
dispatch({type:"TOTAL_DOCTORS",payload:response.data});
console.log(response.data);
})
.catch(function(err){
//console.log(err);
dispatch({type:"TOTAL_DOCTORS_REJECTED",payload:"there was an error rortal doctors"});
})
}
}
doctorReducer
export function doctorsReducers(state={
doctors:[],
}, action){
switch(action.type){
case "GET_DOCTORS":
// return the state and copy of boos array from state
return {...state,doctors:[...action.payload]}
break;
case "TOTAL_DOCTORS":
// return the state and copy of boos array from state
return {
...state,
totalDoctorCount:action.payload
}
break;
}
return state;
}
服务器API
app.get('/doctors/:filterType',function(req,res){
let filterType = req.params.filterType;
var query = {};
if(filterType == "dateCreated"){
query = {date_created: 'desc'};
}else if(filterType == "dateUpdated"){
query = {date_updated: 'desc'};
}
Doctors.find({}).sort(query).limit(3).exec(function(err,doctors){
if(err){
throw err;
}
res.json(doctors);
});
});
app.get('/getTotalDoctors',function(req,res){
Doctors.count({}, function(err, count){
if(err){
throw err;
}
res.json(count);
});
});
成分</ P>
class MainAdmin extends React.Component{
constructor(){
super();
this.state = {
selected_filter:"dateCreated"
};
}
openAddDoctorModal = () => {
this.setState({AddDoctorModal:true});
}
closeAddDoctorModal = () => {
this.setState({AddDoctorModal:false});
}
componentDidMount(){
this.props.getTotalDoctors();
this.props.getDoctors(this.state.selected_filter);
}
loadPage = (pageNum) => {
//alert(pageNum);
this.props.loadPage(pageNum,this.state.selected_filter);
}
render(){
const doctorsList = this.props.doctors.map(function(doctorsArr){
return(
<Col xs={12} sm={12} md={12} key={doctorsArr._id}>
<DoctorsItem
_id = {doctorsArr._id}
doc_fname = {doctorsArr.doc_fname}
doc_lname = {doctorsArr.doc_lname}
/>
</Col>
)
});
//const lengthPage = parseInt(this.props.totalDoctorCount/3);
console.log("this.props.totalDoctorCount2: "+this.props.totalDoctorCount );
const pages = parseInt(this.props.totalDoctorCount/3, 10);
console.log("pages: "+pages );
const pageNums = [...Array(pages)].map((pageNum, i) => {
return(
<Col xs={2} sm={2} md={2} key={i+1}>
<Button onClick={() => this.loadPage(i+1)} bsStyle="success" bsSize="small">
{i+1}
</Button>
</Col>
)
});
return(
<Well>
<Row style={{marginTop:'15px'}}>
{doctorsList}
</Row>
<Row style={{marginTop:'15px'}}>
{pageNums}
</Row>
</Well>
)
}
}
function mapStateToProps(state){
return{
doctors: state.doctors.doctors,
totalDoctorCount:state.doctors.totalDoctorCount
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({
getDoctors:getDoctors,
loadPage:loadPage,
getTotalDoctors:getTotalDoctors
},dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(MainAdmin);
答案 0 :(得分:0)
有几种方法可以解决这个问题,但您必须首先了解如何处理影响dom的异步操作。每当组件安装(并且取决于您如何设置应用程序,每当对props,state等进行更改)时,都会调用其render函数。在您的示例中,组件安装,向服务器询问医生列表,调用render(),然后然后从服务器接收医生列表。换句话说,当它调用render方法时,它还没有从axios调用中收到医生列表。
如果您了解所有这一切,请道歉。现在为什么this.props.totalDoctorCount返回undefined:你的应用程序的state.totalDoctorCount在函数getTotalDoctors结算之前没有被定义(即,从服务器回来)。您可以通过在defaultState中将totalDoctorCount定义为0来解决此问题(您将医生定义为空数组)。
另一方面,你真的希望用户看到/认为总共有0名医生,直到服务器及时响应?这可能是考虑加载组件的好机会。我喜欢做的是在下面&#39; render()&#39;,检查是否存在需要迭代的列表,如果它是空的,你可以返回一个LoadingComponent(你可以在你的拥有并在任何需要加载的地方使用它。这本身是不够的,因为如果您实际上没有任何医生,您不希望页面无限期加载,因此只有在检索列表的函数时才会出现此LoadingComponent它所关注的仍然是“提取”。&#39;因此,也许您可以在获取之前调用三个操作,在响应获取之后,以及是否存在错误。
所以概述:
1)MainAdmin安装。
2)调用GetDoctors和GetTotalDoctors。
3)新动作“正在寻找”&#39;被叫,将你的州留下:
{
doctors: [],
totalDoctors: 0, //assuming you have added this to defaultState
isFetchingDoctors: true
}
4)MainAdmin调用render()。
5)因为state.doctors为空且state.isFetchingDoctors为true,所以MainAdmin.render()返回你的新LoadingComponent。
6)您的服务器使用医生列表和totalDoctorCount响应您的axios呼叫(注意:这将在不同时间发生,但为了简单起见,我将它们视为一起发生)。
7)您的成功处理程序使用新的医生列表更新您的州:
{
doctors: [1, 2, 3],
totalDoctors: 3,
isFetchingDoctors: true
}
8)由于状态的改变,MainAdmin再次调用render(),但由于state.isFetchingDoctors仍然为true,它仍将显示LoadingComponent。
8)你的第二个新动作isFetched()被调用,你的状态为:
{
doctors: [1, 2, 3],
totalDoctors: 3,
isFetchingDoctors: false
}
9)MainAdmin再次调用render(),但这次表示不再加载条件,你可以安全地遍历你的医生列表。
最后一点说明:您可以在减号机中将“isFetching”设置为“false”,直到“GetDoctors&#39;但我个人喜欢将异步状态函数分离到它们自己的函数中,以保持每个函数的座右铭,只需要做一件事。