image.png

  1. store
  2. --index.js
  3. --reducer.js

1.创建store(容器),管理数据

  1. //1.创建store导入下面的文件 index.js
  2. import {createStore} from 'redux' //1.引入
  3. import reducer from './reducer' //3.导入
  4. //createStore()里面只能接受函数
  5. //3.
  6. let store=createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) //配置redux调式工具
  7. export default store;

2.创建reducer,接收action,重新计算state

  1. //reducer.js
  2. //2.定义默认的状态
  3. const defaultState={
  4. msg:"这是关于redux"
  5. }
  6. export default(state=defaultState,action)=>{
  7. return state
  8. }

3.在组件中导入store,使用

  1. import store from '../store/index'
  2. this.state=store.getState()

4.组件中派发action,通过一个事件

  1. <p>{this.state.msg}</p>
  2. <button onClick={this.handleClick}>改变reducex</button>
  3. handleClick=()=>{
  4. //创建action
  5. const action={
  6. type:"btn_value",
  7. value:"redux很难用"
  8. }
  9. //派发action
  10. store.dispatch(action)
  11. }

5.store自动接收action,之后将action传递给reducer

  1. //reducer可以接收state,但是不能直接修改state
  2. export default(state=defaultState,action)=>{
  3. console.log(action)
  4. switch(action.type){
  5. case "btn_value":
  6. var newState={...state};
  7. newState.msg=action.value;
  8. return newState;
  9. default:
  10. return state
  11. }
  12. }
  1. class Home extends Component {
  2. constructor(props){
  3. ...
  4. this.state=store.getState()
  5. store.subscribe(this.handleSotreChange)
  6. }
  7. handleSotreChange=()=>{
  8. this.setState(store.getState())
  9. }
  10. }