------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)