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

Sim*_*ton 5 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;
Run Code Online (Sandbox Code Playgroud)

起初我没有注意到它,但是从我最近理解的情况来看,上面的代码或多或少地遵循了这种redux-thunk模式......所以从那里我尝试应用redux-thunk但我无法做任何工作......

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

谢谢.

小智 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)
);
Run Code Online (Sandbox Code Playgroud)

对于加载异步数据,即使它是初始状态,您也需要调度操作.如果您正在使用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);
Run Code Online (Sandbox Code Playgroud)

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

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

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