如何應用React + Redux + Thunk伺服器獲取資料範例ajax、axios

10 月 5, 2018 | | 0 comments

簡單來說applyMiddleware是使action中能做更多的事情,如同去賦予執行action有能力在中間去多執行function,不同只是傳遞資料參數,thunk則在中間扮演著處理非同步問題。

Thunk應用增加延遲2秒

const { createStore, applyMiddleware } = Redux;
const { Provider, connect } = ReactRedux
const thunk = ReduxThunk.default
const Increment = () =>{
  return function (dispatch){
    setTimeout(()=>{
      dispatch({type: 'INCREMENT'})
    },2000)
  }
  // return {
  //     type: 'INCREMENT'
  // }
}
class Counter extends React.Component {
  render() {
    console.log(this.props);
    return (
      

Counter

{this.props.count}
) } } const actionsCreators = (dispatch)=> { return{ increment: () => { //store.dispatch({ type: 'INCREMENT' }); dispatch(Increment()) }, decrement : () => { dispatch({ type: 'DECREMENT' }); } } } function mapStateToProps(state) { console.log(state); return { count: state.count }; } const Concounter = connect(mapStateToProps,actionsCreators)(Counter); const initialState = { count: 0 }; function reducer(state = initialState, action) { switch(action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } } const store = createStore(reducer,window.devToolsExtension ? window.devToolsExtension() : undefined ,applyMiddleware(thunk)); const App = () => ( ); ReactDOM.render(, document.getElementById('root'));

DEMO 1

Thunk axios AJAX load資料範例展示

const { createStore, applyMiddleware } = Redux;
const { Provider, connect } = ReactRedux
const thunk = ReduxThunk.default

const loadLorem = () => {
  return (dispatch) => {
    // console.log("****")
    axios.get("https://baconipsum.com/api/?type=all-meat&sentences=1&start-with-lorem=0")
      .then(response => {
        // console.log(response.data)
        dispatch({type: 'CHANGE_SENTENCE', sentence: response.data[0]})
      }
    )
  }
}

const defaultState = {
  sentence: "Waiting for load"
}

const mainReducer = (prevState = defaultState, action) => {
  if (action.type === "CHANGE_SENTENCE") {
    return {...prevState, sentence: action.sentence}
  }
  else if (action.type === "TEST") {
    return {...prevState, sentence: action.value}
  }
  else {
    return prevState
  }
}

const MessageBox = (props) => {
  return 
{ props.message }
} const mapStateToProps = state => state const actionsCreators = { loadLorem: loadLorem, testAction: () => ({type: 'TEST', value: 'VALUE'}) } const store = createStore(mainReducer, applyMiddleware(thunk)) // const store = createStore(mainReducer) const App = (props) => { return
} const AppConnected = connect(mapStateToProps, actionsCreators)(App) // const AppConnected = connect(mapStateToProps, mapDispatchToProps)(App) ReactDOM.render(, document.getElementById('root'));

DEMO 2