react redux
App.js
import React, { Component } from 'react'; import store from './redux'; import Com from "./com" class App extends Component { constructor(props){ super(props); console.log(store); console.log(store.getState());//获取数据 this.save = this.save.bind(this); this.state = { message: "", inputValue: "" }; store.subscribe(this.handleStoreChange);//监听store中的state改变 } render() { return ( <div className="App"> <input value = {this.inputValue} onChange={this.inputChange} /> <button onClick={this.save}>存储state</button> <p>{this.state.message}</p> <Com /> </div> ); } save(){ const action = { type: "msg",//必须有 value: this.state.inputValue } store.dispatch(action);//改变redux/reducer.js的state } handleStoreChange = () => { this.setState((preState) => { const newState = JSON.parse(JSON.stringify(preState)); const storeData = store.getState(); console.log(storeData) newState.message = storeData.message; return newState; }); } inputChange = (e) => { const value = e.target.value; this.setState((preState) => { const newState = JSON.parse(JSON.stringify(preState)); newState.inputValue = value; return newState; }); } } export default App;
redux/index.js import { createStore } from 'redux'; import reducer from './reducer.js'; export default createStore(reducer);
redux/reducer.js export default (state = {}, action) => { console.log(state,action); const newState = JSON.parse(JSON.stringify(state)); if(action.type == "msg"){ newState.message = action.value; return newState; } if(action.type == "msg-msg"){ newState.message = action.value; return newState; } return newState; }