一.目录文件夹
二.各文件详细信息
1.store/index.js
// 创建store,再导出
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './reducers/index'
import { composeWithDevTools } from 'redux-devtools-extension'
// thunk中间件允许在 action 里执行异步操作
import thunk from 'redux-thunk'
const middlewares = composeWithDevTools(applyMiddleware(thunk))
const store = createStore(rootReducer, middlewares)
export default store
2.store/reducer/index.js(翻转reducer中各文件的配置信息)
import { combineReducers } from 'redux'
import login from './login'
import user from './user'
import channel from './channel'
import article from './article'
const rootReducer = combineReducers({
login,
user,
channel,
article
})
export default rootReducer
3.store/actionType.js
4.store/actions/login.js
5.store/reducer/login.js
三.在react中使用redux
1.修改redux
import { useDispatch } from 'react-redux'
import { useLogin } from '@/store/actions/login'
const Login = (props) => {
const dispatch = useDispatch()
const onFinish = async (value) => {
try {
await dispatch(useLogin(value))
} catch (err) {
message.error(err.response.data.message, 1)
}
}
return (
<button onClick={onClick}>调用redux</button>
)
}
2.使用redux中的数据
import { useSelector } from 'react-redux'
const Login = (props) => {
// redux 中有xxx就用 state.xxx 获取数据,可以在浏览器中通过redux调试工具查看
const count = useSelector((state) => state.count)
return (
<h1>{count}</h1>
)
}
四.redux执行图解