参考文档
一、安装依赖
yarn add redux
二、项目配置
store
--index.js
--reducer.js
2-1 创建store(容器),管理数据
//index.js
import {createStore} from 'redux';
import reducer from './reducer';
const store = createStore(reducer);
export default store;
2-2 创建reducer,接收action,重新计算state
let defaultState={
msg:"redux",
list:[]
}
// reducer可以接受state,但是不能直接修改state
export default (state=defaultState,action)=>{
switch (action.type) {
case "change_input_value":
let newState = {...state};
newState.msg = action.value
return newState;
case "add_todo_item":
let nState = {...state};
if(nState.msg!==""){
nState.list.push(nState.msg)
nState.msg = ""
}
return nState
case "delete_todo_item":
let yState = {...state};
yState.list.splice(action.value,1)
return yState
default:
return state
}
}
2-3 在Home.js导入store(需要在那个组件中使用,就在那里导入)
import store from '../store'js
class Home extends Component {
constructor(props) {
super(props);
this.state = getState();
}
....
}
2-4 Action
View发出的一个通知,要改变state
//通过一个事件派发action
1.创建一个ation,同时派发
import React, { Component } from 'react';
import store from '../store'
class Home extends Component {
constructor(props) {
super(props);
this.state = store.getState();
}
render() {
return (
<div>
首页
<button onClick={this.handleClick}>改变store</button>
</div>
);
}
handleClick=()=>{
const action = {
type:"btn_change",
value:"复习redux"
}
store.dispatch(action)
}
}
export default Home;
//2.store自动接收action,之后将action传递给reducer
//3.在reducer改变state
let defaultState = {
msg:"react"
}
//reducer可以接收state,但是不能直接修改state
export default (state=defaultState,action)=>{
console.log(action)
switch(action.type){
case "btn_change":
var newState = {...state};
newState.msg = action.value;
return newState;
default:
return state;
}
}
//4.订阅store的状态的改变,只要store改变,store.subscribe(fn),fn函数必然会执行
class Home extends Component {
constructor(props) {
...
store.subscribe(this.handleStoreChange);
}
...
handleStoreChange=()=>{
console.log(1)
this.setState(store.getState())
}
}
三、基本概念
store 就是保存数据的地方,将store看成一个容器,一个应用只能有一个store
//如何生成一个store createStore
//store--index.js
import { createStore } from 'redux'
const defaultState = {
msg:"react很不好用"
}
const reducer = (state=defaultState,action)=>{
return state;
}
// createStore只能接收函数
let store = createStore(reducer);
export default store;
reducer 就是对state重新计算的过程就是reducer,reducer必须是函数
四、redux的调试
1.chrome应用商店安装redux
https://github.com/zalmoxisus/redux-devtools-extension
//2.配置
import { createStore } from 'redux'
import reducer from './reducer'
// createStore只能接收函数
let store = createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
export default store;