【问题标题】:Passing context into React Thunk?将上下文传递给 React Thunk?
【发布时间】:2018-03-05 16:59:22
【问题描述】:

我想我对我应该如何使用 thunk 感到困惑......我的理解是我可以使用它来调度这样的异步操作:

app/index.ts

import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import reducer from "./reducers/index";

const store = createStore(reducer, {}, applyMiddleware(thunk));

ReactDOM.render(
   <Provider store={store}>
     <App />
   </Provider>,
   document.getElementById("root") as HTMLElement,
);

actions.ts

export interface RemoveDoneAction {
  type: TypeKeys.REMOVE_DONE;
  done: Task;
}

export const removeDone: ThunkAction<Promise<void>, Task, {}> =
  (dispatch, getState) => {
    const done = getState();
    return done.delete() // Call API
    .then(() => {        // Send Action
        const action: RemoveDoneAction = {
          type: TypeKeys.REMOVE_DONE,
          done,
        };
        dispatch(action);
    });
  };

todo.tsx

import * as React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import { removeDone } from "./actions";

interface IDoneProps {
  doneList: Task[];
  dispatch: Dispatch<{}>;
}

class Done extends React.Component<IDoneProps, {}> {

  public removeFromDone = (index: number) => {
    const todo = this.props.doneList[index];

    //call thunk action!
    removeDone(this.props.dispatch, () => (todo), {}).then(() => {
      console.log("thunk then!");
    });
  } 

 public render() {
    //create a item from each done
    const doneItems = this.props.doneList.map((done, i) => {
      return (
        <TodoItem
          text={done.description}
          key={i}
          index={i}
          icon="close"
          iconColor="#d67866"
          onClick={this.removeFromDone}
        />
      );
    });

    return (
      <Card title={`${this.props.doneList.length} todo${this.props.doneList.length > 1 ? "s" : ""} done`}>
        <ul>
          {doneItems}
        </ul>
      </Card>);
  }
}


export default connect((state) => {
  return { doneList: state.done };
})(Done);

虽然这完全可行,但我意识到我正在将上下文传递给状态,而不是将任何内容传递给 extraArgs...

我什至不明白为什么 thunk 需要访问状态,因为它只是将操作分派给减速器?!

我怀疑我做的不对...

【问题讨论】:

    标签: typescript redux redux-thunk


    【解决方案1】:

    好的,我在这篇文章的帮助下想通了...

    基本上,我的动作创建者应该是这样的:

    export const removeDone = (done: Task): ThunkAction<Promise<void>, GlobalState, null> =>
      (dispatch, getState) => {
        return done.delete().then(() => {
          console.log(getState());
          const action: RemoveDoneAction = {
            type: TypeKeys.REMOVE_DONE,
            done,
          };
          dispatch(action);
        });
      };
    

    要调用,我只是通过动作创建者和redux中间件句柄注入状态。

    this.props.dispatch(removeDone(todo));
    

    这更有意义......

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2020-06-25
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2018-02-03
      • 1970-01-01
      相关资源
      最近更新 更多