企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
app.js ~~~ import React, { Component } from 'react'; import store from '../store/index.js'; 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(action); } handleStoreChange=()=> { this.setState(store.getState()) } handleAdd=()=>{ const action ={ type:'addItem', value:this.state.inputValue } store.dispatch(action); } handleDelete=(index)=>{ const action ={ type:'deleteItem', index } store.dispatch(action); } }; export default App; ~~~ src>store>reducer.js ~~~ // 相当于仓库 const defaultState={ inputValue:'hello world', list:[] }; /* state指store中的数据 */ export default (state=defaultState,action)=>{ console.log(action); if(action.type==='inputChange'){ //解构复制一份 let newState = {...state} newState.inputValue = action.value; return newState; } if(action.type==='addItem'){ //解构复制一份 let newState = {...state} newState.list.push(action.value); return newState; } if(action.type==='deleteItem'){ let newState = {...state} newState.list.splice(action.index,1); return newState; } return state; } ~~~ src>store>index.js ~~~ import {createStore} from 'redux'; import reducer from './reducer'; const store = createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); export default store; ~~~