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)
相关推荐
Setsuna_F_Seiei1 小时前
前端转型 Agent 开发 05 之 Agent Hooks 与 Checkpointer(让 Agent 从全自动转变人为可掌控)
前端·agent·ai编程
百万蹄蹄向前冲3 小时前
风扇转了一晚上MVP专家团翻车事故
前端·人工智能
默_笙3 小时前
🏛 给 AI 配一间办公室:Harness Engineering 六大模块与它的实现
前端·javascript
linux_cfan5 小时前
videojs v10 源代码系列解读:14 · 谓词守卫:在运行时安全地调用能力
前端·javascript·音视频
狗狗狗狗狗乐啊5 小时前
搭一个 AI 对话工作台 AChat:从 0 到可用的完整记录(一)
python·react.js·ai编程
kyriewen5 小时前
我扒了 10,221 条 JD:腾讯技术岗 75% 在要 AI
前端·人工智能·ai编程
郑州光合科技余经理6 小时前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
IT_陈寒6 小时前
Vue的响应式让我熬到凌晨三点,原来漏了这个小细节
前端·人工智能·后端
Blanche15006 小时前
利用 RAG 为答疑机器人扩展知识范围
前端
天若有情6737 小时前
【纯前端小工具】公历生日转农历,批量查询每年农历生日对应的公历日期(GitHub Pages在线直接用)
前端·javascript·github pages·农历转换·lunisolar·网页小工具