React Redux 服务器端渲染但客户端获取数据
React Redux 服务器端渲染但客户端获取数据
我正在我的演示react应用程序上进行服务器渲染。虽然如果我刷新页面访问像/doctor/:id这样的url时确实会起作用,但如果我在/login且尝试进入/doctor/123456时,doctor属性为空,(this.props.doctor.name.first)失败。
使用redux获取这些情况下的数据的好方法是什么?
代码如下
import { fetchDoctor } from '../../DoctorActions'; import { getDoctor } from '../../DoctorReducer'; class DoctorDetailPage extends Component { render() { return ( {this.props.doctor.name.first} ); } } 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);
REDUCER
import { ADD_DOCTOR } from './DoctorActions'; // Initial State const initialState = { list: [] }; const DoctorReducer = (state = initialState, action = {}) => { switch (action.type) { case ADD_DOCTOR: return { list: [action.doctor, ...state.list], }; default: return state; } }; export const getDoctor = (state, id) => { return state.doctors.list.filter(doctor => doctor._id === id)[0]; }; export default DoctorReducer;
ACTIONS
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))); }; }
LOG ERROR
TypeError: Cannot read property 'name' of undefined
admin 更改状态以发布 2023年5月23日
通用的获取数据的好方法是什么?
一个用户友好的方式是,在不需要医生的情况下进入页面 /doctor/123456
,这样用户可以立即得到反馈,确认他的操作(将我导航到页面 x)成功了。在 react-router 的 onEnter
方法或 componentDidMount
中,你应该启动一个 fetchDoctor
动作,在此同时向用户显示一个旋转器或指示数据正在加载的消息。
render() { return ( { this.props.doctor && {this.props.doctor.name.first} } { ! this.props.doctor &&} ); }
因此,上述的渲染方法在数据加载时显示一些内容,当数据加载完成时,可以无错误地显示它。
Redux 中获取数据的好方法是什么?
传统的处理异步操作的方式是使用 redux-thunk
。你可以阅读这个关于通过异步方式派发 Redux 动作的很棒的 SO 答案。
最新的趋势是使用redux-saga
。它是一个旨在使 React/Redux 应用程序中的副作用(即数据获取和访问浏览器缓存等不纯粹的操作)更加容易和更好的库。有关 redux-saga
的更多信息.
因此,在你的情况下,你将创建一个 Saga 来处理获取数据。