-
import { combineReducers } from 'redux' import countReducer from './modules/count' export const IndexReducers =combineReducers({ countReducer })
2.同步Action
export const increment = value => ({ type: INCREMENT, value }) export const decement = value => ({ type: DECAMENT, value })
-
异步Action:
我在使用redux过程中遇到Actions must be plain objects. Use custom middleware for async actions.异常的分析 //异步Action任务 export const AsyncIncremnet=(data,time)=>{ return ()=>{ setTimeout(()=>{ Store.dispatch(increment(10)) },time) } } //redux不支持传递函数的Action如果必必须那就加上redux-thunk来实现
完整redux
-
import { INCREMENT, DECAMENT } from "../reducers"; //无法使{}直接加上()//这是同步Action export const increment = value => ({ type: INCREMENT, value }) export const decement = value => ({ type: DECAMENT, value }) //异步Action任务 export const AsyncIncremnet=(data,time)=>{ //这是中间件传递过来的dispath return (dispatch)=>{ console.log(dispatch) setTimeout(()=>{ dispatch(increment(10)) },time) } } const defaultState = { count: 0 } export const INCREMENT = 'increment' export default (preState = defaultState, action) => { const { type, value } = action switch (type) { case INCREMENT: console.log({ ...preState, count: preState.count += value }) return { ...preState, count: preState.count += value }; default: return { ...preState } } } import { combineReducers } from 'redux' import countReducer from './modules/count' export const IndexReducers =combineReducers({ countReducer }) //当时为了方便直接写在这里 export const INCREMENT = 'increment' export const DECAMENT='delete' import {createStore,applyMiddleware} from 'redux' import {IndexReducers} from '../reducers/index.js' import ReduxThunk from 'redux-thunk' export const Store=createStore(IndexReducers,applyMiddleware(ReduxThunk)) import React, { Component } from 'react' import './App.css'; import { Store } from './store/store.js' import { INCREMENT } from './reducers/index' import {increment,decement,AsyncIncremnet} from './actions/count' export default class App extends Component { state = {...Store.getState().countReducer}; componentDidMount() { Store.subscribe(() => { this.setState(Store.getState().countReducer); }) } decement=()=>{ decement(10) }; increment=()=>{ increment(10) } render() { console.log(this.state) const { count } = this.state; return ( <div>t APP... { count} <button onClick={()=>{Store.dispatch(AsyncIncremnet(10,500))}}>Async点击INCremet</button> <button onClick={()=>{Store.dispatch(increment(10))}}>点击INCremet</button> <button onClick={()=>Store.dispatch(decement(10))}>点击INCremet</button> </div> ) } } // export default App;
版权声明:本文为qq_42577176原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。