Reactjs React Redux服务器渲染,但客户端获取数据
我正在我的一个演示react应用程序上进行服务器渲染。虽然如果我刷新url上的页面以获取类似于/doctor/:id的医生(如果我在/login并尝试转到/doctor/123456),它仍然有效,但医生属性为空并且(this.props.doctor.name.first)失败 使用redux获取这些案例的数据的好方法是什么 代码如下Reactjs React Redux服务器渲染,但客户端获取数据,reactjs,redux,react-router,react-redux,isomorphic-javascript,Reactjs,Redux,React Router,React Redux,Isomorphic Javascript,我正在我的一个演示react应用程序上进行服务器渲染。虽然如果我刷新url上的页面以获取类似于/doctor/:id的医生(如果我在/login并尝试转到/doctor/123456),它仍然有效,但医生属性为空并且(this.props.doctor.name.first)失败 使用redux获取这些案例的数据的好方法是什么 代码如下 import { fetchDoctor } from '../../DoctorActions'; import { getDoctor } from '..
import { fetchDoctor } from '../../DoctorActions';
import { getDoctor } from '../../DoctorReducer';
class DoctorDetailPage extends Component {
render() {
return (
<div>{this.props.doctor.name.first}</div>
);
}
}
DoctorDetailPage.need = [params => {
return this.props.dispatch(fetchDoctor(params.id));
}];
function mapStateToProps(state, props) {
return {
doctor: getDoctor(state, props.params.id),
};
}
DoctorDetailPage.propTypes = {
doctor: PropTypes.shape({
insurance: PropTypes.string,
description: PropTypes.string,
GUID: PropTypes.string,
name: PropTypes.shape({
first: PropTypes.string,
last: PropTypes.string,
})
}),
dispatch: PropTypes.func.isRequired,
};
export default connect(mapStateToProps)(DoctorDetailPage);
行动
import callApi from '../../util/apiCaller';
// Export Constants
export const ADD_DOCTOR = 'ADD_DOCTOR';
// Export Actions
export function addDoctor(doctor) {
return {
type: ADD_DOCTOR,
doctor,
};
}
export function addDoctorRequest() {
return () => {
return true;
};
}
export function fetchDoctor(id) {
return (dispatch) => {
return callApi(`doctors/${id}`)
.then(res => dispatch(addDoctor(res)));
};
}
日志错误
TypeError: Cannot read property 'name' of undefined
一般来说,什么是获取数据的好方法?
一种用户友好的方法是进入页面/doctor/123456
,而不需要医生在场,这样用户可以立即得到反馈,知道他的操作(将我导航到第x页)有效。在react router的oneter
方法或componentDidMount
中,您应该启动一个操作fetchDoctor
,同时向用户显示一个微调器或一条消息,指示正在加载数据
render() {
return (
<div>
{ this.props.doctor && <div>{this.props.doctor.name.first}</div> }
{ ! this.props.doctor && <YourSpinnerComponent/> }
</div>
);
}
render(){
返回(
{this.props.doctor&&{this.props.doctor.name.first}
{!this.props.doctor&&}
);
}
因此,上面的render方法在加载数据时显示一些内容,当数据进入时,它会显示这些内容,而不会出现任何错误
使用redux获取数据的好方法是什么?
处理异步操作的“好方法”是使用。你可以读这个
最新趋势是使用。它是一个库,旨在使React/Redux应用程序中的副作用(即数据获取等异步操作和访问浏览器缓存等不纯净操作)变得更简单、更好
因此,在您的案例中,您将创建一个传奇来处理抓取
.控制台中显示的错误是什么?“TypeError:无法读取未定义”的属性“name”,因为医生未定义。虽然服务器端正在工作,但客户端获取失败。您能否切换到“网络”选项卡,并告诉我们是否在客户端正确进行了API调用?否。这就像在解析该对象之前尝试渲染一样。另外,唯一的解决方法是使用componentDidMount函数并将医生状态设置为空。这种方式可以将其显示为空,然后用获取的数据替换它。但这不是重复的方法谢谢你的回答很好。只是想让其他用户知道,如果您将return()放在一个div中,上面的示例就可以了,如。。return(Hello!{this.props.doctor&&{this.props.doctor.name.first})@Panagiotisvr感谢您的留言。我也更正了答案。
render() {
return (
<div>
{ this.props.doctor && <div>{this.props.doctor.name.first}</div> }
{ ! this.props.doctor && <YourSpinnerComponent/> }
</div>
);
}