我应该如何使用“redux-thunk”进行异步初始状态? (反应/终极版)

时间:2016-08-11 23:09:21

标签: reactjs redux redux-thunk

这个问题已经被问了好几次,但是我并没有真正理解我找到的答案。使用React / Redux,我试图通过express将异步数据放入我的初始状态。因为我习惯了d3,我的一个选择是使用“d3.json”...但如果它更好的话,我会很乐意使用别的东西。从以前对同一主题的回答中,我添加了以下代码:

// redux action using a dispatcher (think middleware)
export function cool(url) {
    return function(dispatch) {
        return d3.json(url, response => {
            dispatch(setData(response))
        }
    }
}

// redux action
export function setData(data) {
 return {
        type: 'DATA_CHART_ALL',
        data
    }
}

const authorDataReducer = (state = {}, action) => {
    switch (action.type) {
      case 'DATA_CHART_ALL':
        return action.data
      case 'DATA_CHART_FILTER':
        return action.data
      default:
        return state;
    }
};

export authorDataReducer;

我一开始并没有注意到它,但根据我最近的理解,上面的代码或多或少遵循redux-thunk模式...所以从那里我尝试应用redux-thunk但我无法做任何事情......

不确定我的问题是否清楚,能帮助减轻这一切是很好的。

感谢。

1 个答案:

答案 0 :(得分:10)

你的问题不是很明确,但我会尽力回答。 Redux-thunk是一种用于调度异步操作的中间件。您在创建redux存储时初始化它:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

const store = createStore(
    rootReducer,
    applyMiddleware(thunk)
);

对于加载异步数据,即使初始状态为异常,您也需要发送操作。如果您正在使用react,则可以在安装最高阶组件时执行此操作。

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

import { fetchTodos } from '../action';
import TodoList from './TodoList';

class App extends Component {

    constructor(props) {
        super(props);
    }

    componentWillMount() {
        this.props.fetchTodos();
    }

    render() {
        return (
            <TodoList
                todos={this.props.todos}
            />
        );
    }
}

App.propTypes = {
    todos: PropTypes.array.isRequired
};

const mapStateToProps = (state, ownProps) => ({
    todos: state.todos
});

export default connect(
    mapStateToProps,
    {
        fetchTodos: fetchTodos
    }
)(App);

这将触发一个看起来像这样的行动

export const fetchTodos = () => {
    return (dispatch) => {
        return fetch(url).then((response) => {
            disptach({
                 type: 'received_todos',
                 payload: {
                     response.json()
                 }
            });
        });
    }
}

正如您所看到的,我没有使用d3而是fetch。我猜任何图书馆都是好的,只要你回来了承诺。