React Redux 服务器呈现但客户端获取数据

React Redux server render but client side fetch data

我在我的演示 React 应用程序上进行服务器渲染。尽管如果我在 url 上刷新页面以获取像 /doctor/:id 这样的医生如果我在 /login 并尝试去 /doctor/123456 医生 属性 是空的并且 (this.props.doctor.name.first) 失败了。

在这些情况下使用 redux 获取数据的好方法是什么?

代码如下

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 { 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;

操作

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 的 onEnter 方法或 componentDidMount 中,你应该开始一个动作 fetchDoctor 并同时向用户显示一个微调器或一条消息,表明正在加载数据。

render() {
    return (
        <div>
          { this.props.doctor && <div>{this.props.doctor.name.first}</div> }
          { ! this.props.doctor && <YourSpinnerComponent/> }
        </div>
    );
}

所以上面的渲染方法在加载数据时显示了一些东西,当数据进来时它显示它没有任何错误。

使用 redux 获取数据的好方法是什么?

处理异步操作的“好旧”方式是使用redux-thunk. You can read this

最新趋势就是用redux-saga. It is a library that aims to make side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better. More about redux-saga.

因此在您的情况下,您将创建一个 Saga 来处理提取。

.