关于redux使用的整理

------actions.js-------

export const CHANGE_MSG = 'CHANGE_MSG'

export function changeMsgAction(payload) {
  return {
    type: CHANGE_MSG,
    payload
  }
}

// 异步操作
export function changeMsgAsyncAction(payload) {
  //报错
  // setTimeout(() => {
  //   return {
  //     type: CHANGE_MSG,
  //     payload
  //   }
  // },2000)

  // 正确写法
  return function (dispatch) {
    setTimeout(() => {
      dispatch({
        type: CHANGE_MSG,
        payload
      })
    },2000)
  }
}

----reducer.js---------

import {
  CHANGE_MSG
} from '../actions'

let initState = {
  msg: 'hello'
}

export default function reducer(state = initState, action) {
  let newState = JSON.parse(JSON.stringify(state))
  switch (action.type) {
    case CHANGE_MSG:
      newState.msg = action.payload
      return newState
    default:
      return newState
  }
}

------store index.js------

------store index.js------
import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import msgReducer from './reducers/msgReducer'

const rootReducer = combineReducers({
  test: msgReducer
})
const store = createStore(rootReducer, applyMiddleware(thunk))

export default store

----app根组件-----

import React from 'react'
import { Provider } from 'react-redux'
import store from './store'
import Home from './pages/Home'
function App() {
  return (
    <Provider store={store}>
      <div className="App">
        <Home></Home>
      </div>
    </Provider>
  );
}

export default App;

-------Home组件----------

import React from 'react'
import { connect } from 'react-redux'
import {changeMsgAction,changeMsgAsyncAction} from '../store/actions'


function Home(props) {
  console.log(props)
  const clickHandle = () => {
    props.changeMsg('你好')
  }
  const clickHandle2 = () => {
    props.changeMsgAsync('异步的')
  }
  return (
    <div>
      home page
      <div>{props.msg}</div>
      <button onClick={clickHandle}>changeMsg</button>
      <button onClick={clickHandle2}>asyncChange</button>
    </div>
  )
}
function mapStateToProps(store) {
  return {
     msg: store.test.msg
  }
}

function mapActionsToProps(dispatch) {
  return {
    // changeMsg: function (payload) {
    //   return dispatch({
    //     type: 1,
    //     payload
    //   })
    // }
    // changeMsg: payload => dispatch({type: 1, payload})
    changeMsg: payload => dispatch(changeMsgAction(payload)),
    changeMsgAsync: payload => dispatch(changeMsgAsyncAction(payload))
  }
}
export default connect(mapStateToProps, mapActionsToProps)(Home)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值