redux & react-redux结合使用 2024

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 App() {
  return (
      <Provider store={store}>
          <div>
              <ComA/>
              <ComB/>
          </div>
      </Provider>
  );
}
export default App;

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 (
            <button onClick={this.handleClick}>+</button>
        )
    }
}
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 (
            <button>{this.props.count}</button>
        )
    }
}
const mapStateToProps=state=>{
    return state
}
export default connect(mapStateToProps)(ComB)
相关推荐
写代码的小王吧1 小时前
【安全】Web渗透测试(全流程)_渗透测试学习流程图
linux·前端·网络·学习·安全·网络安全·ssh
小小小小宇2 小时前
CSS 渐变色
前端
snow@li2 小时前
前端:开源软件镜像站 / 清华大学开源软件镜像站 / 阿里云 / 网易 / 搜狐
前端·开源软件镜像站
小小小小宇2 小时前
配置 Gemini Code Assist 插件
前端
one 大白(●—●)3 小时前
前端用用jsonp的方式解决跨域问题
前端·jsonp跨域
刺客-Andy3 小时前
前端加密方式 AES对称加密 RSA非对称加密 以及 MD5哈希算法详解
前端·javascript·算法·哈希算法
记得早睡~3 小时前
leetcode122-买卖股票的最佳时机II
javascript·数据结构·算法·leetcode
前端开发张小七3 小时前
13.Python Socket服务端开发指南
前端·python
前端开发张小七3 小时前
14.Python Socket客户端开发指南
前端·python
ElasticPDF-新国产PDF编辑器3 小时前
Vue 项目 PDF 批注插件库在线版 API 示例教程
前端·vue.js·pdf