网站搜索

typescript - 将上下文传递到 React Thunk?


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

应用程序/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 需要访问状态,因为它只是向 reducers 分发动作?!

我怀疑我做得不对……

答案#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));

这更有道理了...