# react18-2024 **Repository Path**: linlilover/react18-2024 ## Basic Information - **Project Name**: react18-2024 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-07-13 - **Last Updated**: 2024-07-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # redux教程2024 ## 1.安装redux ```yarn add redux /npm i redux``` ## 2.创建目录 ```action/reducer/store``` ## 3.编写action ```js const sendAction=()=>{ return { type:'send_type', value:'i am action' } } module.exports={ sendAction } ``` ## 4.编写reducer ```js const initState={ value:'init' } const reducer=(state=initState,action)=>{ console.log(state,action) switch (action.type){ case "send_type": return Object.assign({},state,action) default: return state } } module.exports={ reducer } ``` ## 5.编写store,reducer与store关联 ```js import {createStore} from "redux"; import {reducer} from '../reducer' const store=createStore(reducer) export default store ``` ## 6.测试store ```js import React from "react"; import store from "../../store"; import {sendAction} from '../../action' export default class Home extends React.Component{ handClick=()=>{ const action=sendAction() store.dispatch(action) } componentDidMount() { store.subscribe(()=>{ console.log("subscribe:",store.getState()) this.setState({}) }) } render() { return ( <>
{store.getState().value}
) } } ``` # redux & react-redux结合使用 2024 ## 1.安装 redux react-redux ``` yarn add redux && yarn add react-redux ``` ## 2.编写reducer ```js const initstate={count:0} exports.reducer=(state=initstate,action)=>{ switch (action.type){ case "add_action": return { count: state.count+1 } default: return state; } } ``` ## 3.编写store ```js import {createStore} from "redux"; import {reducer} from '../reducer' const store=createStore(reducer) export default store ``` ## 4.根组件引入provider ```js import Home from "./pages/home"; import ComA from "./pages/ComA"; import ComB from "./pages/ComB"; import store from "./store"; import {Provider} from "react-redux"; function App1() { return (
); } export default App1; ``` ## 5.发送状态 ```js import React from "react"; import {connect} from "react-redux"; class ComA extends React.Component{ handleClick=()=>{ console.log(111) this.props.sendAction() } render() { return ( ) } } const mapDispatchToProps=(dispatch)=>{ return { sendAction:()=>{ dispatch({ type:'add_action' }) } } } export default connect(null,mapDispatchToProps)(ComA) ``` ## 6.接收状态 ```js import React from "react"; import {connect} from "react-redux"; class ComB extends React.Component{ render() { return ( ) } } const mapStateToProps=state=>{ return state } export default connect(mapStateToProps)(ComB) ```