【问题标题】:How do I deal with d3.json to get my InitialState in React/redux如何处理 d3.json 以在 React/redux 中获取我的 InitialState
【发布时间】:2016-12-14 14:52:41
【问题描述】:

使用 React/Redux,我正在尝试使用 express 将外部数据转换为我的初始状态。我习惯使用 D3,所以我想像这样将 d3.json 与我的减速器一起使用:

var url = 'http://localhost:3000/authors';

function cool() {
d3.json(url, function(data) {
dataset = data;
 });
}

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

export default authorData;

由于 D3.json 是一个回调函数,我的减速器返回未定义。我该如何处理?我可以使用 d3.json 以外的东西吗?

【问题讨论】:

    标签: json reactjs redux


    【解决方案1】:

    你需要一个在 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;
    

    使用它:

    在您的应用程序开始时调用它:

    store.dispatch(cool("MY_URL"));
    

    请注意,我没有检查请求中的错误处理

    【讨论】:

    • 是的。谢谢。我想出了相同的解决方案。但是我想知道是否还有其他解决方案...
    • 我回到这个,因为它不起作用。我有这个错误ncaught TypeError: (0 , _index2.default) is not a function ...?
    • 嘿 DOMZE,我已经提出了另一个问题,我认为这里可以更好地表达我的问题:link。我试图打开一个 JSbin,但我无法让它工作jsbin.com/xocopal/15/edit?html,js,console,output
    • 你不能直接在浏览器中使用 ES6。您必须打包(使用 webpack 或使用 polyfill 进行编译
    • 你说的是 jsbin 吗?
    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多