企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
1.首先先封装action中的type ~~~ //src=>store=>actionType.js // 集中管理action中的type,方便调试 const inputChange="inputChange"; const addItem="addItem"; const deleteItem="deleteItem"; export{inputChange,addItem,deleteItem}; ~~~ 2.封装action ~~~ //src=>store=>actionCreators.js // 直接将action进行封装使用 import {inputChange,addItem,deleteItem} from "./actionType.js"; const valueChangeAction=(value)=>{ return { type:inputChange, value } } const valueaddItemAction=(value)=>{ return { type:addItem, value } } const valuedeleteItemAction=(index)=>{ return { type:deleteItem, index } } export{valueChangeAction,valueaddItemAction,valuedeleteItemAction} ~~~ 3.使用 ~~~ //app.js import React, { Component } from 'react'; import store from '../store/index.js'; // import {inputChange,addItem,deleteItem} from "../store/actionType.js" //导入的type import {valueChangeAction,valueaddItemAction,valuedeleteItemAction} from "../store/actionCreators" //导入的是action class App extends Component { //动态显示时数据 构造器 constructor(props) { super(props); console.log(store.getState()) this.state = store.getState(); // 只要store的状态改变就会触发(要通过事件获取reducer中的数据,多个数据时也只使用一个) store.subscribe(this.handleStoreChange) } // 固定格式返回一个html1 render() { return ( <div> <input value={this.state.inputValue} onChange={this.handleChange}/> <button onClick={this.handleAdd}>添加</button> <div> {this.state.list.map((value,index)=>{ return( <div onClick={()=>{this.handleDelete(index)}} key={index}> {value} </div> ) })} </div> </div> ); } handleChange = (e) => { // const action ={ // type:inputChange, // value:e.target.value // } store.dispatch(valueChangeAction(e.target.value)); } handleStoreChange=()=> { this.setState(store.getState()) } handleAdd=()=>{ // const action ={ // type:addItem, // value:this.state.inputValue // } store.dispatch(valueaddItemAction(this.state.inputValue)); } handleDelete=(index)=>{ // const action ={ // type:deleteItem, // index // } store.dispatch(valuedeleteItemAction(index)); } }; export default App; ~~~