2016-08-11 94 views
2

这个问题已经有好几次了,但是我并没有真正理解我找到的答案。使用React/Redux,我试图用异步将异步数据放入我的初始状态。由于我习惯于d3,我的一个选择是使用“d3.json”......但如果效果更好,我会很乐意使用其他的东西。从同一主题的一个以前的答案我添加以下代码:我应该如何使用“redux-thunk”作为Async Initial状态? (react/redux)

// 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,但我不能做任何工作...

不知道如果我的问题是明确的,将是很好的一些帮助,以减轻所有这一切。

谢谢。

回答

5

你的问题不是很清楚,但我会尽力回答。 Redux-thunk是您用来分派异步操作的中间件。你初始化的时候了Redux店beeing创建为这样:

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

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

对于异步加载数据,你需要派遣一个动作,即使它的初始状态。如果您正在使用反应,那么当您的最高顺序组件已装入时,可以对此进行响应

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。我想任何一个图书馆都是好的,只要你返回一个承诺。

+0

当我在我的'connect'中添加'{fetchTodos:fetchTodos}'时,出现以下错误'finalMergeProps不是函数' –

+0

fetchTodos应该是您导入的操作。连接中的{fetchTodos:fetchTodos}只是一种将动作映射到道具的方式,以便您可以在组件 –

+0

中将它称为“this.props.fetchTodos”。我是否需要对减速器做任何事情?当你说承诺你是什么意思?再次感谢 ! –

相关问题