react-thunk demo使用示例(初步使用)

其实我什么都不懂,可是我什么都想知道,至少知道怎么使用也是棒棒的吧!前端

今天在一家环境很好的咖啡厅开始个人react学习,这篇文章的目的就是为了让和我同样刚开始接触react-thunk的前端小菜鸟看的哈,主要就是运做一下react-thunk的使用。react

咱们知道,react中涉及到异步操做,那react-thunk就是为了咱们在dispatch(action)的过程当中,action是异步的解决办法出现的,固然,还有别的中间件哟,本处就不涉及了。redux

题目: 当咱们输入input,点击提交按钮的时候,延迟一秒将咱们的输入显示在UI层app

解决:框架

基于react框架,咱们先写出UI:

index.js:异步

handleInputChange(e){
    this.setState({
      inputValue:e.target.value,
    })
  }

  handleInputSubmit(e){
   // const value = e.target.value;
    this.props.todo(this.state.inputValue);
    this.setState({
      inputValue:'',
    })
  }
     
 render(){
   return (
          <input onChange={this.handleInputChange.bind(this)} value={this.state.inputValue} />
      <div className='button' onClick={this.handleInputSubmit.bind(this)}>提交</div>
      <div style={{background:'',color:'black',fontSize:'20px',textAlign:'left'}}>
         {this.props.todos.map((item,index)=>{return <div key={index}>{item}</div>})}
      </div> 
   )
 }
 
 const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    ** todo:(text)=>{dispatch(addTodo(text))}, **
  }
}

const mapStateToProps = (state) => {
  return {
    todos:state.todos
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App)

store.js学习

import { createStore , applyMiddleware } from 'redux' ;
import reducer from '../reducer';
import ReduxThunk from 'redux-thunk';

let store = createStore(reducer,applyMiddleware(ReduxThunk));
console.log('store.getState()=',store.getState())
export default store;

action.jsthis

export default function addTodo(text) {
  return dispatch=>{
    console.log('dispatch=',dispatch)
    setTimeout(
      ()=>{
        dispatch({ type: ADD_TODO, text })
      },2000) 
   }
}

reduce.jsspa

export default function todos(state = [], action) {
    switch (action.type) {
      case 'ADD_TODO':
        return state.concat([action.text])
      default:
        return state
    }
  }

以上代码是完整流程代码,供你们参考,实现一个简单的react-thunk过程。code

参考action.js ,react-thunk 主要为咱们异步处理过程当中传递了一个dispatch,方便咱们在异步过程当中dispatch一个对象。

UI图以下:

clipboard.png

总结: demo代码已经完整献上,道行深浅就看本身了。加油呀!

相关文章
相关标签/搜索