我觉得我对如何使用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发送动作?!
我怀疑我做得不对......
答案 0 :(得分:0)
好的,我在本文的帮助下弄清楚了......
基本上,我的动作创建者应该看起来像这样:
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));
这更有意义......