2017-09-24 82 views
0

我覺得我對我怎麼想使用咚......我的理解是,我可以用它來調度異步操作這樣的困惑:將上下文傳遞給React 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 ...

我甚至不明白爲什麼會形實轉換需要訪問因爲它只是向減速器發出行動?

我懷疑我不是在做正確的事情......

回答

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 middlewear處理。

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

這使得很多更有意義......