React-Redux
是Redux
的官方React
绑定库。它能够使你的React
组件从Redux store
中读取数据,并且向store
分发actions
以更新数据
1.react项目搭建 npx create-react-app app
2.安装redux npm i redux
3.安装 react-redux npm i react-redux
组件,能够使你的整个app访问到Redux store
中的数据:src/index.js
import React from "react";
import { createRoot } from 'react-dom/client'
import App from './App.jsx'
// 引入
import store from './store'
// 引入 react-redux
import { Provider } from 'react-redux'
const root = createRoot(document.getElementById('root'))
root.render(
)
src/store/index.js
import { createStore, combineReducers } from 'redux'
import{ num,books} from './reducer.js'
// 合并
const rootReducer = combineReducers({books,num})
const store = createStore(rootReducer)
export default store
src/store/reducer.js
import {NUM_ADD,NUM_REDUCE,BOOKS_ADD} from './reducer-types'
export function num(state = 0, action) {
console.log('action', action);
switch (action.type) {
case NUM_ADD:
return state + action.payload
case NUM_REDUCE:
return state - action.payload
default:
return state
}
}
export function books(state = ['redux', 'react-redux'], action) {
switch (action.type) {
case BOOKS_ADD:
return [action.payload, ...state]
default:
return state
}
}
src/store/reducer-types.js
export const NUM_ADD = '/num/add'
export const NUM_REDUCE='/num/reduce'
export const BOOKS_ADD = '/books/add'
src/App.jsx
import React from "react";
import { connect } from 'react-redux'
import Hook from "./Hook";
import {NUM_ADD,NUM_REDUCE,BOOKS_ADD} from './store/reducer-types'
class App extends React.Component {
handlerAdd = () => {
this.props.subCount()
}
handlerReduce = () => {
this.props.divideCount(1)
}
render() {
let {num,books,addBooks} = this.props
return (
<>
app组件(类组件)--- num:{num}
{books.map((item,index)=>(- {item}
))}
>
)
}
}
// state 仓库数据
// props 父亲传递过来的数据
const mapStateToProps = (state, props) => ({...state,...props })
// 方法
const mapDispatchToProps = dispatch => (
{
subCount: () => dispatch({ type: NUM_ADD, payload: 10 }),
divideCount: (payload) => dispatch({ type: NUM_REDUCE, payload }),
addBooks: (payload) => dispatch({ type: BOOKS_ADD, payload })
}
)
// 位置不能颠倒
export default connect( mapStateToProps,mapDispatchToProps)(App)
import{ useSelector,useDispatch } from 'react-redux'
import {BOOKS_ADD,NUM_ADD} from './store/reducer-types'
function Hook(){
// 获取
let num = useSelector(({num})=>num)
let books = useSelector((state)=>state.books)
let dispatch = useDispatch()
let bookeredux = ()=>{
dispatch({type:BOOKS_ADD,payload:'node'})
}
return(
<>
Hook组件---num:{num}
{books.map((item,index)=>(- {item}
))}
>
)
}
export default Hook