如何在 redux 中的 ajax 请求后转换路由

How to transition routes after an ajax request in redux

我想知道以下内容的正确模式是什么...

我有一个 HomeComponent,其中有一些指向其他组件的链接。 当我单击其中一个链接时,我想发出 ajax 请求以获取该组件的初始状态。

dispatchHomeComponentonClick吗?或者在没有来自服务器的 initialState 的情况下在其他组件中分派一个动作? (我正在做一个通用应用程序,所以如果我直接点击其他组件之一,初始状态已经存在,但来自我的 HomeComponent,数据不会存在)

这就是我到目前为止的...

class HomeComponent extends React.Component {
  navigate(e) {
    e.preventDefault();

    // Fetch data here
    actions.fetch(1234);

    // When do I call this?
    browserHistory.push(e.target.href);
  }
  render() {
    const links = [
      <a href="/foo/1247462" onClick={this.navigate}>Link 1</a>,
      <a href="/foo/1534563">Link 2</a>,
    ];

    return (
      <ul>
        {links.map((link) => (
          <li>{link}</li>
        ))}
      </ul>
    );
  }
}

抱歉我可以添加评论,你有没有使用 react-redux && redux-thunk 的原因?

你的要求可以通过这些轻松完成:你在 mapDispatchToProps 中获取你需要的内容并使用获取的初始状态分派一个动作

你的 reducer 会捕捉到上述分派的 action 并更新它的状态,这将在 mapStateToProps 的帮助下更新反应组件的 props

凭记忆写的,可能不是100%准确:

redux 文件

componentNameReducer = (
    state = {
        history: ''
    },
    type = {}
) => {
    switch(action.type) {
        case 'HISTORY_FETCHED_SUCCESSFULLY':
            return Object.assign({}, state, {
                history: action.payload.history
            });
        default:
            return state;
    }
};

mapStateToProps = (state) => {
    history: state.PathToWhereYouMountedThecomponentNameReducerInTheStore.history
};

mapDispatchToProps = (dispatch) => ({
    fetchHistory : () => {
        fetch('url/history')
            .then((response) => {
                if (response.status > 400) {
                    disptach({
                        type: 'HISTORY_FETCH_FAILED',
                        payload: {
                            error: response._bodyText
                        }
                    });
                }
                return response;
            })
            .then((response) => response.json())
            .then((response) => {
                //do checkups & validation here if you want before dispatching
                dispatch({
                    type: 'HISTORY_FETCHED_SUCCESSFULLY',
                    payload: {
                        history: response
                    }
                });
            })
            .catch((error) => console.error(error));
    }
});

module.exports = {
    mapStateToProps,
    mapDispatchToProps,
    componentNameReducer
}

在你的 React 组件上你会 need :

import React, {
    Component    
} from 'somewhere';

import { mapStateToProps, mapDispatachToProps } from 'reduxFile';
import { connect } from 'react-redux';

class HistoryComponent extends Component {
    constructor(props){
        super(props);
        this.props.fetchHistory(); //this is provided by { connect } from react-redux
    }
    componentWillReceiveProps(nextProps){
        browserHistory.push(nextProps.history);
    }
    render() {
        return (

        );
    }
}
//proptypes here to make sure the component has the needed props

module.exports = connect(
    mapStateToProps,
    mapDispatachToProps
)(HistoryComponent);